How can one implement OO in Lua?

后端 未结 5 1929
自闭症患者
自闭症患者 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:26

    For a quick and dirty oo implementation I do something like -

    function newRGB(r,g,b)
      return {
        red=r;
        green=g;
        blue=b;
        name='';
        setName = function(self,name)
          self.name=name;
        end;
        getName = function(self)
          return self.name;
        end;
        tostring = function(self)
          return self.name..' = {'..self.red..','..self.green..','..self.blue..'}'
        end
      }
    end
    

    which can then be used like -

    blue = newRGB(0,0,255);
    blue:setName('blue');
    
    yellow = newRGB(255,255,0);
    yellow:setName('yellow');
    
    print(yellow:tostring());
    print(blue:tostring());
    

    for a more full featured approach I would use an oo library as was mentioned by eemrevnivek. You can also find a simple class function here which is somewhere between full on library and quick and dirty.

提交回复
热议问题