lua-users home
lua-l archive

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


On Jan 14, 2008 11:42 AM, Grellier, Thierry <t-grellier@ti.com> wrote:
> In that case, I don't understand why then not returning a class table to
> benefit Lua unaltered and compact syntax?

If you want Python-style class declarations, you can do that simply enough:

function class(body)
    local mt = {G = _G}
    mt.__index = mt
    setfenv(body,mt)
    body()

    function mt.new()
        local self = {}
        setmetatable(self,mt)
        return self
    end

    return mt
end

animal = class(function()
    function speak(self)
        G.print ('growl '..self:get_name())
    end

    function set_name(self,s)
        self.name = s
    end

    function get_name(self)
        return self.name
    end
end)

a = animal.new()
a:set_name 'fido'
a:speak()

With a little extra macro sugar, this is a quite painless syntax!

Multiple inheritance can be implemented with a little extra trouble,
and you can probably get a proper global context as well for the
methods, as well.

steve d.