Inheritance in Lua

筅森魡賤 提交于 2020-01-23 10:01:30

问题


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?


回答1:


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



回答2:


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.




回答3:


In newClass, your second call to setmetatable simply overwrites the first one. The following shorter function will give you the expected behavior:

function newClass(new_class, super)
  new_class = new_class or {}

  -- This assumes single inheritance. Multiple inheritance would require a
  -- function for __index.
  if super then
    setmetatable(new_class,{__index = super})
  end

  return new_class

end


来源:https://stackoverflow.com/questions/29758313/inheritance-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!