Hi,
I’d like to ask for some explanation for metatables in lua.
I’ve read a bunch of tutorials on this already, but nothing really worked for me. Only got me more doubts and confusion.
What I already know is that any table in lua can have a metatable, which can contain anything, but they respond to certain keys.
My first question would be about this syntax:
t = setmetatable({}, {})
I see almost everyone use this syntax. This is a “shorter” way to make a table and give it a metatable. I put shorter in quotes cause it only saves you 2 lines of code and to me it only looks confusing.
And how does it even make sense?
It looks like we stored a function in a variable and gave it 2 empty tables for arguments, the first one being the base table and the second one is the metatable. And I guess we don’t have to name the metatable, since if we need it we can get it with getmetatable(). Correct me if I’m wrong, please.
Next, I’m having my mind blown by operator keys like __mul or __add.
This for example is some random code I found somewhere on the internet:
t = setmetatable({ 1, 2, 3 }, { \_\_mul = function(t, other) new = {} for i = 1, other do for \_, v in ipairs(t) do table.insert(new, v) end end return new end }) t = t \* 2 -- { 1, 2, 3, 1, 2, 3 }
In the above example- what’s the point of using the multiplication operator if we don’t really multiply tables. We just defined what happens to tables once they’re passed as arguments and then return a completely new table. Couldn’t we have done exactly the same using the addition operator? Or any other operator? I can’t see the point of having so many operators.
And I guess I understand most other metatable keys…kinda.
For now I just need some help with the above things.