Lua面向对象编程:定时器实现
2011-7-2 8:47:29
收藏:0
阅读:128
评论:1
我正在遵循这个教程 http://www.crawlspacegames.com/blog/inheritance-in-lua/,创建了两个对象(架子鼓和吉他)从 MusicalInstrument 继承。在我添加计时器函数之前,一切都很正常,然后由于某种原因 ,只有一个从 MusicalInstrument 继承的对象被调用。
MusicalInstrument.lua:
module(...,package.seeall)
MusicalInstrument.type="undefined"
local function listener()
print("timer action: "..MusicalInstrument.type)
end
function MusicalInstrument:play(tpe)
MusicalInstrument.type = tpe;
print("play called by: "..MusicalInstrument.type)
timer.performWithDelay(500,listener,3)
end
function MusicalInstrument:new( o )
x = x or {} -- 可以参数化,默认为新表
setmetatable(x, self)
self.__index = self
return x
end
Guitar.lua
module(...,package.seeall)
require("MusicalInstrument")
gtr = {}
setmetatable(gtr, {__index = MusicalInstrument:new()})
return gtr
Drums.lua
module(...,package.seeall)
require("MusicalInstrument")
drms = {}
setmetatable(drms, {__index = MusicalInstrument:new()})
return drms
main.lua
-- CLEAR TERMINAL --
os.execute('clear')
print( "clear" )
--------------------------
local drms=require("Drums")
drms:play("Drums")
local gtr=require("Guitar")
gtr:play("Guitar")
这是终端输出:
clear
play called by: Drums
play called by: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
我期望输出有 3 个吉他计时器调用和 3 个鼓计时器调用
如何使它工作的任何想法都会非常感谢!!
谢谢
----------------------------- 编辑后另一次尝试 -------------------
在 MusicalInstrument 中所做的以下更改
module(...,package.seeall)
MusicalInstrument.type="undefined"
function MusicalInstrument:listener()
print("timer action: "..MusicalInstrument.type)
end
function MusicalInstrument:play(tpe)
MusicalInstrument.type = tpe;
print("play called by: "..MusicalInstrument.type)
timer.performWithDelay(500,MusicalInstrument:listener(),3)
end
function MusicalInstrument:new( o )
x = x or {} -- 可以参数化,默认为新表
setmetatable(x, self)
self.__index = self
return x
end
导致以下输出:
clear
play called by: Drums
timer action: Drums
play called by: Guitar
timer action: Guitar
正确的乐器被计时器调用,但仅一次。
原文链接 https://stackoverflow.com/questions/6555889
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在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 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
在
listener
和MusicalInstrument:play()
中,您为两个实例写入和读取相同的变量。实际上,您希望在每个实例中设置乐器类型。Lua 不是我的主要语言,但例如:
function MusicalInstrument:listener() print("timer action: "..self.type) end function MusicalInstrument:play(tpe) self.type = tpe; local f = function() self:listener() end timer.performWithDelay(500, f, 3) end