Alex Rivera | Logout

How can one implement OO in Lua?

Asked 2011-01-25T21:30:46.753
23

Lua does not have build in support for OO, but it allows you to build it yourself. Could you please share some of the ways one can implement OO?

Please write one example per answer. If you have more examples, post another answer.

Edit
Report

1 Answer

2

The approach I use usually goes like this:

class = {} -- Will remain empty as class
mt = {} -- Will contain everything the instances will contain _by default_

mt.new = function(self,foo)
    local inst={}
    if type(foo) == "table" then
         for k,v in pairs(foo) do
             inst[k]=v
         end
    else
        inst.foo=foo
    end
    return setmetatable(inst,getmetatable(class))
end

mt.print = function(self)
    print("My foo is ",self.foo)
end

mt.foo= 4 --standard foo

mt.__index=mt -- Look up all inexistent indices in the metatable

setmetatable(class,mt)

i1=class:new() -- use default foo
i1:print()

i2=class:new(42)
i2:print()

i3=class:new{foo=123,print=function(self) print("Fancy printing my foo:",self.foo) end}

Well, conclusion: with metatables and some clever thinking, about anything is possible: metatables are the REAL magic when working with classes.

answered 2011-01-30T20:47:43.977

Your Answer