Firstly, let me just say that these questions aren’t really suited for the devforum. I understand you have questions, and I’ve been there myself, but there are already hundreds of people who have asked the same question and given a better answer than I probably could. Please try to do research to find previous answers instead of creating new threads.
Aside from that, let’s break this down linearly into steps:
First, your code creates table metatable
with a function at index __call
. Note that __call
is a metamethod, so when it is present in a metatable it will be used as a stand-in function when a table with this metatable is called using parentheses, like a function normally would.
Next, your code creates a new table, {10,20,30}
, and sets its metatable to be the table you defined above. This means that when you perform actions with or on said table that may trigger a metamethod, lua will try to find specific metamethods in the table’s metatable, this being the metatable
table you defined in the first step. (If this needs clarifying, setmetatable
returns the first argument passed to it)
After that, you take your table t
and attempt to call it with parentheses, similar to how a function would be called. Because you’re not calling a function, you’re actually calling a table, Lua tries to find a specific metamethod in the table t
’s metatable that it can use as a stand-in, so that the code can function correctly without errors. Specifically it is looking for a metamethod at the index __call
, and it’s expecting the value at that index to be a function. Since we know that table t
’s metatable is the table metatable
that you defined above, and we can see that there is indeed a function at index __call
that Lua will find, it’s clear that lua will use this function instead as it’s stand-in replacement.
Finally, once Lua has found it’s stand-in function at index __call
, it attempts to call said function, passing the table you initially attempted to call, t
, as the first argument, and the actual arguments you passed in the function call as arguments 2,3, etc. Once the function is finished calling, it will return it’s value, which Lua will forward and use as the return value for your initial call of t
. This is why you see 15,20, and 25 as your printed values, because the return values of __call
are what the initial call returns to you.
I hope that sufficed as an in-depth explanation, let me know if you have any further questions!