[ACCEPTED]-How to create a class, subclass and properties in Lua?-lua

Accepted answer
Score: 10

Here's an example literal transcription 17 of your code, with a helpful Class library that 16 could be moved to another file.

This is by 15 no means a canonical implementation of Class; feel 14 free to define your object model however 13 you like.

Class = {}

function Class:new(super)
    local class, metatable, properties = {}, {}, {}
    class.metatable = metatable
    class.properties = properties

    function metatable:__index(key)
        local prop = properties[key]
        if prop then
            return prop.get(self)
        elseif class[key] ~= nil then
            return class[key]
        elseif super then
            return super.metatable.__index(self, key)
            return nil

    function metatable:__newindex(key, value)
        local prop = properties[key]
        if prop then
            return prop.set(self, value)
        elseif super then
            return super.metatable.__newindex(self, key, value)
            rawset(self, key, value)

    function class:new(...)
        local obj = setmetatable({}, self.metatable)
        if obj.__new then
        return obj

    return class

ElectronicDevice = Class:new()

function ElectronicDevice:__new()
    self.isOn = false

ElectronicDevice.properties.isOn = {}
function ElectronicDevice.properties.isOn:get()
    return self._isOn
function ElectronicDevice.properties.isOn:set(value)
    self._isOn = value

function ElectronicDevice:Reboot()
    self._isOn = false
    self._isOn = true

Router = Class:new(ElectronicDevice)

Modem = Class:new(ElectronicDevice)

function Modem:WarDialNeighborhood(areaCode)
    local cisco = Router:new()
    if self._isOn then

If you were to stick to get/set 12 methods for properties, you wouldn't need 11 __index and __newindex functions, and could just have an 10 __index table. In that case, the easiest way to 9 simulate inheritance is something like this:

BaseClass = {}
BaseClass.index = {}
BaseClass.metatable = {__index = BaseClass.index}

DerivedClass = {}
DerivedClass.index = setmetatable({}, {__index = BaseClass.index})
DerivedClass.metatable = {__index = DerivedClass.index}

In 8 other words, the derived class's __index table 7 "inherits" the base class's __index table. This 6 works because Lua, when delegating to an 5 __index table, effectively repeats the lookup on 4 it, so the __index table's metamethods are invoked.

Also, be 3 wary about calling obj.Method(...) vs obj:Method(...). obj:Method(...) is syntactic sugar 2 for obj.Method(obj, ...), and mixing up the two calls can produce 1 unusual errors.

Score: 7

There are a number of ways you can do it 2 but this is how I do (updated with a shot 1 at inheritance):

function newRGB(r, g, b)
  local rgb={
      red = r;
      green = g;
      blue = b;
      setRed = function(self, r)
          self.red = r;
      setGreen = function(self, g)
          self.green= g;
      setBlue = function(self, b)
          self.blue= b;
      show = function(self)
          print("red=",self.red," blue=",self.blue," green=",self.green);
  return rgb;

purple = newRGB(128, 0, 128);

---// Does this count as inheritance?
function newNamedRGB(name, r, g, b)
    local nrgb = newRGB(r, g, b);
    nrgb.__index = nrgb; ---// who is self?
    nrgb.setName = function(self, n)
        self.name = n;
    nrgb.show = function(self)
        print(name,": red=",self.red," blue=",self.blue," green=",self.green);
    return nrgb;

orange = newNamedRGB("orange", 180, 180, 0);

I don't implement private, protected, etc. although it is possible.

Score: 4

If you don't want to reinvent the wheel, there 2 is a nice Lua library implementing several 1 object models. It's called LOOP.

Score: 3

The way I liked to do it was by implementing 12 a clone() function.
Note that this is for 11 Lua 5.0. I think 5.1 has more built-in 10 object oriented constructions.

clone = function(object, ...) 
    local ret = {}

    -- clone base class
    if type(object)=="table" then 
            for k,v in pairs(object) do 
                    if type(v) == "table" then
                            v = clone(v)
                    -- don't clone functions, just inherit them
                    if type(v) ~= "function" then
                            -- mix in other objects.
                            ret[k] = v
    -- set metatable to object
    setmetatable(ret, { __index = object })

    -- mix in tables
    for _,class in ipairs(arg) do
            for k,v in pairs(class) do 
                    if type(v) == "table" then
                            v = clone(v)
                    -- mix in v.
                    ret[k] = v

    return ret

You then 9 define a class as a table:

Thing = {
   a = 1,
   b = 2,
   foo = function(self, x) 
     print("total = ", self.a + self.b + x)

To instantiate 8 it or to derive from it, you use clone() and 7 you can override things by passing them 6 in another table (or tables) as mix-ins

myThing = clone(Thing, { a = 5, b = 10 })

To 5 call, you use the syntax :


That will print:

total = 115

To 4 derive a sub-class, you basically define 3 another prototype object:

BigThing = clone(Thing, { 
     -- and override stuff.  
     foo = function(self, x)

This method is 2 REALLY simple, possibly too simple, but 1 it worked well for my project.

Score: 2

It's really easy to do class-like OOP in 10 Lua; just put all the 'methods' in the __index field 9 of a metatable:

local myClassMethods = {}
local my_mt = {__index=myClassMethods}

function myClassMethods:func1 (x, y)
    -- Do anything
    self.x = x + y
    self.y = y - x


function myClass ()
    return setmetatable ({x=0,y=0}, my_mt)

Personally, I've never needed 8 inheritance, so the above is enough for 7 me. If it's not enough, you can set a metatable 6 for the methods table:

local mySubClassMethods = setmetatable ({}, {__index=myClassMethods})
local my_mt = {__index=mySubClassMethods}

function mySubClassMethods:func2 (....)
    -- Whatever

function mySubClass ()
    return setmetatable ({....}, my_mt)

update: There's an error 5 in your updated code:

Router = {};
mt_for_router = {__index=Router}
--Router inherits from ElectronicDevice
Router = setmetatable({},{__index=ElectronicDevice});

Note that you initialize 4 Router, and build mt_for_router from this; but then you reassign 3 Router to a new table, while mt_for_router still points to 2 the original Router.

Replace the Router={} with the Router = setmetatable({},{__index=ElectronicDevice}) (before 1 the mt_for_router initialization).

Score: 1

Your updated code is wordy, but should work. Except, you 17 have a typo that is breaking one of the 16 metatables:

--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index,ElectronicDevice});

should read

--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index=ElectronicDevice});

The existing fragment 15 made the Modem metatable be an array where the 14 first element was almost certainly nil (the 13 usual value of _G.__index unless you are using strict.lua or 12 something similar) and the second element 11 is ElectronicDevice.

The Lua Wiki description will make sense after 10 you've grokked metatables a bit more. One 9 thing that helps is to build a little infrastructure 8 to make the usual patterns easier to get 7 right.

I'd also recommend reading the chapter 6 on OOP in PiL. You will want to re-read the 5 chapters on tables and metatables too. Also, I've 4 linked to the online copy of the 1st edition, but 3 owning a copy of the 2nd is highly recommended. There 2 is also a couple of articles in the Lua Gems book 1 that relate. It, too, is recommended.

Score: 1

Another simple approach for subclass

local super    = require("your base class")
local newclass = setmetatable( {}, {__index = super } )
local newclass_mt = { __index = newclass }

function newclass.new(...) -- constructor
    local self = super.new(...)
    return setmetatable( self, newclass_mt )

You 4 still can use the functions from superclass 3 even if overwritten

function newclass:dostuff(...)
   -- more code here --

don't forget to use ONE 2 dot when pass the self to the superclass 1 function

More Related questions