How can one implement OO in Lua?

后端 未结 5 1944
自闭症患者
自闭症患者 2021-02-01 06:04

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

5条回答
  •  不要未来只要你来
    2021-02-01 06:32

    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.

提交回复
热议问题