lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> I want to synthesize properties on the base class using __index and __newindex so that they're available to all instances.

To add methods to "all instances" of a class, you just add methods to
the table that's the __index field on every instance's metatable, like
so:

    Sprite = {}

    sprite1 = setmetatable({x=1}, {__index = Sprite})
    sprite2 = setmetatable({x=2}, {__index = Sprite})

    Sprite.foobar = function(self) return self.x * 10 end
    -- alternatively but functionally equivalent:
    function Sprite:foobar() return self.x * 10 end

    sprite1:foobar() -- returns 10
    sprite2:foobar() -- returns 20

To turn this into multi-level inheritance, you can just do this:

    SpriteBase = {}
    Sprite = setmetatable(Sprite, {__index = SpriteBase})

Now, just add methods to SpriteBase, and both sprite1 and sprite2 have them.