I did not know what to name this question as I don't understand enough of what is going on.(Feel free to edit)
Consider the code below.
function object:new()
o = o or {
x = 0
}
setmetatable(o, self)
self.__index = self
self.y = 0
return o
end
table = object:new()
What are the differences between the variables (o.x and self.y) later on?
If I print_r the variable table, only the x is returned. However, both table.x and table.y can be accessed. This makes me realise that there is a difference between the two.
Could someone explain what the difference is and what reasons there are for putting variable in differant places?
You have two tables here,
objectando.Inside of
object:new,selfrefers to the tableobject. Soself.yis a field in the tableobject.ois the new table you create in each call toobject:new.o.xis a field in the tableo.That
otable only has one entry:o["x"], so when you iterate over the entries in the table (asprint_rdoes), that's all you're going to see.So why does
o.ygive you a value? Because you set the tableobjectaso's metatable and that metatable has it's__indexfield set, so when an index attempt fails ono, Lua will try again viao's metatable (if it has __index set).A little code will probably make this clearer: