Lua: When is it possible to use colon syntax? -
while understand basic difference between . , :, haven't figured out when lua allows use colon syntax. instance, work:
s = "test" -- type(s) string. -- can write colon function type function string:myfunc() return #self end -- , colon function calls possible s:myfunc() however same pattern not seem work other types. instance, when have table instead of string:
t = {} -- type(t) table. -- can write colon function type function table:myfunc() return #self end -- surprisingly, colon function call not not possible! t:myfunc() -- error: attempt call method 'myfunc' (a nil value) -- verbose dot call works table.myfunc(t) moving on type:
x = 1 -- type(x) number. -- expecting can write colon function -- type well. however, in case -- fails: function number:myfunc() return self end -- error: attempt index global 'number' (a nil value) i'm trying make sense of this. correct conclude
- certain types
stringallow both colon-function-definitions and colon-function-calls. - other types
tableallow colon-function-definitions not colon-function-calls. - yet other types
numberallow neither.
what reason these differences? there list of types, showing type of colon-syntax support? there maybe workaround number case, allowing write e.g. x:abs()?
the first example on string works because, strings share same metatable, , it's stored in table named string.
from string:
the string library provides functions inside table
string. sets metatable strings__indexfield pointsstringtable. therefore, can use string functions in object-oriented style. instance,string.byte(s,i)can writtens:byte(i).
the second example on table doesn't work because, every table has own metatable, table named table collection of functions of table library.
types numbers don't support metatable default.
Comments
Post a Comment