CrazyAmphibian
CrazyAmphibian

Reputation: 13

lua and methods, confusion

i'm trying to figure out how to make methods for use in my code, and it's quite confusing to me

i tried using this code:

string.testfunc = function(s) print(s) end
a="foo"
a:testfunc() --inputting a non-string value into the function gives an error

>foo

i then tried this bit of code

table.testfunc = function(s) print(s[1]) end
a={1,2}
table.testfunc(a)

>1

a:testfunc() --this will always error, no matter the type of the varible

>method 'testfunc' is not callable (a nil value)

how come i can create a method in the string table and have it work fine with strings but not with tables? and how come making one with tables doesn't work?

Upvotes: 1

Views: 176

Answers (1)

lhf
lhf

Reputation: 72312

The string library in Lua sets an index metamethod for all strings.

The table library in Lua does not set an index metamethod for all tables, because tables are used to represent objects. Typically objects of the same class share the same metatable.

Upvotes: 2

Related Questions