Lua 继承和方法
2021-6-3 23:50:28
收藏:0
阅读:172
评论:1
如何从类 actor 继承一个名为 player 的新类,并使方法 actor:new(x, y, s) 在方法 player:new(x, y, s) 中被调用,参数相同。我需要让 player:new 与 actor:new 一样,但是还需要额外的参数,以便 player 拥有比 actor 更多的属性。
是否有一种方法不只在 new 方法中实现这个功能,而是在其他方法中,例如 player:move(x, y) 将调用 actor:move(x, y) 或 self:move(x, y) ,但附加其他代码?
我使用以下模式在模块中创建类:
local actor = {}
function actor:new(x, y, s)
self.__index = self
return setmetatable({
posx = x,
posy = y,
sprite = s
}, self)
end
-- methods
return actor
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

一个好的方法是有一个单独的初始化实例的函数。然后你可以在继承的类中简单地调用基类的初始化。
像这个例子:http://lua-users.org/wiki/ObjectOrientationTutorial
function CreateClass(...) -- "cls" is the new class local cls, bases = {}, {...} -- copy base class contents into the new class for i, base in ipairs(bases) do for k, v in pairs(base) do cls[k] = v end end -- set the class's __index, and start filling an "is_a" table that contains this class and all of its bases -- so you can do an "instance of" check using my_instance.is_a[MyClass] cls.__index, cls.is_a = cls, {[cls] = true} for i, base in ipairs(bases) do for c in pairs(base.is_a) do cls.is_a[c] = true end cls.is_a[base] = true end -- the class's __call metamethod setmetatable(cls, {__call = function (c, ...) local instance = setmetatable({}, c) -- run the init method if it's there local init = instance._init if init then init(instance, ...) end return instance end}) -- return the new class table, that's ready to fill with methods return cls end你可以简单地这样做:
actor = CreateClass() function actor:_init(x,y,s) self.posx = x self.posy = y self.sprite = s end player = CreateClass(actor) function player:_init(x,y,s,name) actor.init(self, x,y,s) self.name = name or "John Doe" end