Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in Lua

I am trying to make a simple api that eases the process of creating classes and sub-classes.

function newClass(index,...)
  local new_class = {}

  setmetatable(new_class,{__index = index})

  local optionalArgs = {...}
  if optionalArgs[1] ~= nil then
      setmetatable(new_class,optionalArgs[1])
  end

  return new_class

end

--TESTINGCODE
exampleSuper = newClass({name="Super",id=1,getName = function() print("Super") end,})
exampleSuper.getName()
exampleSub = newClass({name="Sub",},exampleSuper)
print(exampleSub.id)

The problem is that even though I create a new super class called exampleSuper, it's fields aren't given to the exampleSub class. How can I change my code to allow my function to define a sub class?

like image 754
Andrew Lalis Avatar asked Sep 11 '25 20:09

Andrew Lalis


2 Answers

This question is well answered in Object-Oriented Programming chapter of Programming In Lua, specifically in the Inheritance section.

In your particular case, when optionalArgs[1] ~= nil check is true, you don't set __index in the metatable as you overwrite your earlier assignment.

like image 161
Paul Kulchenko Avatar answered Sep 14 '25 20:09

Paul Kulchenko


Something like this, maybe:

function newClass(new_obj,old_obj)
  old_obj = old_obj or {}               --use passed-in object (if any)
  new_obj = new_obj or {}
  assert(type(old_obj) == 'table','Object/Class is not a table')
  assert(type(new_obj) == 'table','Object/Class is not a table')
  old_obj.__index = old_obj             --store __index in parent object (optimization)
  return setmetatable(new_obj,old_obj)  --create 'new_obj' inheriting 'old_obj'
end
like image 45
tonypdmtr Avatar answered Sep 14 '25 21:09

tonypdmtr