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,
object
ando
.Inside of
object:new
,self
refers to the tableobject
. Soself.y
is a field in the tableobject
.o
is the new table you create in each call toobject:new
.o.x
is a field in the tableo
.That
o
table only has one entry:o["x"]
, so when you iterate over the entries in the table (asprint_r
does), that's all you're going to see.So why does
o.y
give you a value? Because you set the tableobject
aso
's metatable and that metatable has it's__index
field 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: