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 string allow both colon-function-definitions and colon-function-calls.
  • other types table allow colon-function-definitions not colon-function-calls.
  • yet other types number allow 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 __index field points string table. therefore, can use string functions in object-oriented style. instance, string.byte(s,i) can written s: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

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -