Lua oop - timer implementation
I was following this tutorial http://www.crawlspacegames.com/blog/inheritance-in-lua/ and created 2 objects (drums and Guitar) that inherit from MusicalInstrument. Everything worked fine until I added timer functions, then for some reason only 1 from the 2 objects that inherit from MusicalInstrument gets called
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
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")
This is the terminal output:
clear
play called by: Drums
play called by开发者_StackOverflow中文版: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
timer action: Guitar
I excepted the output to have 3 guitar time calls and 3 drums timer calls
Any ideas on how to make this work will be appreciated much!!
Thanks
----------------------------- Edited after another try -------------------
The following change in 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
Resulted with the following output :
clear
play called by: Drums
timer action: Drums
play called by: Guitar
timer action: Guitar
The correct instruments were called by the timer but only once
In both listener
and MusicalInstrument:play()
you write and read the same variable for both instances.
You actually want to set the instrument type per instance here. Lua is not exactly my primary language, but e.g. something like:
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
精彩评论