OOP inheritance question

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: 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 [import]uid: 65158 topic_id: 11936 reply_id: 311936[/import]

got an answer in stackoverflow :
http://stackoverflow.com/questions/6555889/lua-oop-timer-implementation/6558206#6558206
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
link|edit|flag
edited 14 hours ago

answered 15 hours ago
Georg Fritzsche
34.4k34174 [import]uid: 65158 topic_id: 11936 reply_id: 43597[/import]

You might also consider “duck typing” instead of inheritance.

http://en.wikipedia.org/wiki/Duck_typing [import]uid: 58455 topic_id: 11936 reply_id: 43885[/import]