The key to this mystry is paying close attention to what self is getting set to in each of these function invocations. Both Class:new and Class:setReset contain self.reset = ....

With Class:new(nil, 10) what is really happening is Class.new(Class, nil, 10), in other words self is pointing at the Class table so the reset value is being assigned in that table.

With Obj1:setReset() what is really happing is Obj1.setReset(Obj1) so in this case self is pointing at the Obj1 table. Lua doesn’t have any notion of a class variable vs instance variable. If the desire was to have reset act like a class variable then it has to be explicitly implemented as such:

function Class:setReset()
  Class.reset = true
end

In Lua setting values in tables is not influenced by the existence of __index. The table chaining behavior provided by __index only applies to getting values out of a table.

Just to emphasize the above - Lua has no notion of instances and classes. As far as the Lua runtime is concerned the Class table no different from any other table. We are treating the Class table as a “prototype” for new instances (also tables) by defining values and functions in the Class table which we’d like to avoid having to redefine in each instance tables. The way we get Lua to find those shared values is by establishing a relationship between the instance table and the “class” table using __index.

2 Likes