How can one implement OO in Lua?

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

    This is already answered, but anyway, here's my oop implementation: middleclass.

    That lib provides the bare minimum for creating classes, instances, inheritance, polymorphism and (primitive) mixins, with an acceptable performance.

    Sample:

    local class = require 'middleclass'
    
    local Person = class('Person')
    
    function Person:initialize(name)
      self.name = name
    end
    function Person:speak()
      print('Hi, I am ' .. self.name ..'.')
    end
    
    local AgedPerson = class('AgedPerson', Person) -- or Person:subclass('AgedPerson')
    
    AgedPerson.static.ADULT_AGE = 18 --this is a class variable
    function AgedPerson:initialize(name, age)
      Person.initialize(self, name) -- this calls the parent's constructor (Person.initialize) on self
      self.age = age
    end
    function AgedPerson:speak()
      Person.speak(self) -- prints "Hi, I am xx."
      if(self.age < AgedPerson.ADULT_AGE) then --accessing a class variable from an instance method
        print('I am underaged.')
      else
        print('I am an adult.')
      end
    end
    
    local p1 = AgedPerson:new('Billy the Kid', 13) -- this is equivalent to AgedPerson('Billy the Kid', 13) - the :new part is implicit
    local p2 = AgedPerson:new('Luke Skywalker', 21)
    p1:speak()
    p2:speak()
    

    Output:

    Hi, I am Billy the Kid.
    I am underaged.
    Hi, I am Luke Skywalker.
    I am an adult.
    

提交回复
热议问题