Lua中的继承 [英] Inheritance in Lua

查看:76
本文介绍了Lua中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的api,以简化创建类和子类的过程.

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)

问题在于,即使我创建了一个名为exampleSuper的新超类,也没有将其字段提供给exampleSub类.如何更改代码以允许函数定义子类?

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?

推荐答案

像这样的事情,也许:

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

这篇关于Lua中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆