Re: Inventory system
Posted: Sun Feb 19, 2017 6:54 pm
We're combining two separate issues.
Yours is that you prefer to use Class.__index = Class instead of a separate mtClass = {__index = Class}. (And then assigning a metatable to the instance with one of these.)
Both of these reuse the same table, so no extra ones are created at instantiation, which is good.
The thing with this, is that your version doesn't allow the Class table itself to have a separate __index lookup (pointing anywhere) from what the instance uses.
Yours: instance doesn't have a method -> instance index metamethod points to class -> look for method in class -> if not found, class metamethod points to class itself -> either recursion limit reached, or method not found.
Mine: instance doesn't have a method -> instance index metamethod points to class -> look for method in class -> class metamethod points to some other table, or to nothing -> either way, the method is either found, or it's not.
Not necessarily an issue, and it may be used rarely, but again, it's just a preference of mine to have my options open.
The other issue was the, imo, bigger one; namely that not having either of the above, and using local instance = setmetatable({}, {__index = whatever}) in the constructor always creates a separate {__index = whatever} table each time the constructor is called, so each instance will have a separate metatable, albeit with the same contents. It's plainly a waste of memory.
Yours is that you prefer to use Class.__index = Class instead of a separate mtClass = {__index = Class}. (And then assigning a metatable to the instance with one of these.)
Both of these reuse the same table, so no extra ones are created at instantiation, which is good.
The thing with this, is that your version doesn't allow the Class table itself to have a separate __index lookup (pointing anywhere) from what the instance uses.
Yours: instance doesn't have a method -> instance index metamethod points to class -> look for method in class -> if not found, class metamethod points to class itself -> either recursion limit reached, or method not found.
Mine: instance doesn't have a method -> instance index metamethod points to class -> look for method in class -> class metamethod points to some other table, or to nothing -> either way, the method is either found, or it's not.
Not necessarily an issue, and it may be used rarely, but again, it's just a preference of mine to have my options open.
The other issue was the, imo, bigger one; namely that not having either of the above, and using local instance = setmetatable({}, {__index = whatever}) in the constructor always creates a separate {__index = whatever} table each time the constructor is called, so each instance will have a separate metatable, albeit with the same contents. It's plainly a waste of memory.