【问题标题】:Lua oop - timer implementationLua oop - 定时器实现
【发布时间】:2011-07-03 00:58:03
【问题描述】:

我正在关注本教程 http://www.crawlspacegames.com/blog/inheritance-in-lua/ 并创建了 2 个继承自 MusicalInstrument 的对象(鼓和吉他)。在我添加计时器函数之前一切正常,然后由于某种原因,从 MusicalInstrument 继承的 2 个对象中只有 1 个被调用

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 {} -- can be parameterized, defaults to a new table
    setmetatable(x, self)
    self.__index = self
    return x
end

吉他.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 {} -- can be parameterized, defaults to a new table
    setmetatable(x, self)
    self.__index = self
    return x
end

结果如下:

clear
play called by: Drums
timer action: Drums
play called by: Guitar
timer action: Guitar

计时器调用了正确的工具,但只调用了一次

【问题讨论】:

    标签: oop lua coronasdk


    【解决方案1】:

    listenerMusicalInstrument: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
    

    【讨论】:

    • 你摇滚! @#@ 1234567890
    • 你推荐什么lua资源??
    • @Eran:我只在需要时通过Lua docs 阅读了一下。但话又说回来,我只是在现有的 Lua 代码库中稍微摆弄了一下。
    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多