`__call` doesn't work in my Lua code

I think a simple sample example file explains the longer words

t = {}
t.__call = print
t.__call(1)
t(2)

      

According to the documentation , since t

is a table, a call t

for example t(2)

should be redirected to a call t.__call

for example t.__call(2)

. t.__call

works fine, no problem, but the "syntactic sugar" doesn't work. Here is the output of the above code:

1
lua: test.lua:4: attempt to call global 't' (a table value)
stack traceback:
        test.lua:4: in main chunk
        [C]: in ?

      

What am I missing? Why t(2)

not converted to t.__call(2)

?

+3


source to share


1 answer


__call

is a metamethod and must be set on the table's meta-method, not on the table itself.

t = {}
m = {}
m.__call = print

setmetatable(t, m)

t(2)

      



Look at here. See @Deduplicator's comment for a more concise way to do the same.

+5


source







All Articles