I have what I believe is probably a pretty common use case wherein I have an external module that creates an object. For the sake of example, let’s say this external module creates a bubble. Back in the main file, I create a button to make a bunch of bubbles. After the bubble has been tapped on so many times, I want to “pop” that bubble. Upon popping it, I’d like to send a message to the main file that the overall “bubbles popped” score needs to be updated.
What I’m struggling with is, how do I send the message from the object created in the external module and have the Runtime listen and handle that event in the main file? I thought that using dispatchEvent would do the trick, but when I try to run that, I get a stack overflow error. I quickly mocked up two simple files to show this exchange, the main.lua and the bubble.lua files. The main.lua looks like this:
-- import external code local bubble = require ("bubble") local widget = require ("widget") -- forward declare variables local bubbles\_popped = 0 local w = display.actualContentWidth local h = display.actualContentHeight local bubble\_base\_msg = "Bubbles Popped: " math.randomseed( os.time( ) ) -- functions local function updateScore(event) print("popped") end -- make the global Runtime "listen" for a bubblePop event Runtime:addEventListener( "bubblePop", updateScore) -- create visual container for score local bubbles\_popped\_txt = display.newText({ text = bubble\_base\_msg, x = w\*.5, y = 30 } ) -- create button to make more bubbles local bubble\_maker = widget.newButton( { label = "Make Bubbles!", x = w\*.5, y = h - 30, onRelease = function() for i = 1, 10 do local newBubble = bubble.makeBubble() newBubble.x = w \* (math.random(1,9)\*.1) newBubble.y = h \* (math.random(2,8)\*.1) end end } )
the external module, where the bubble is created, looks like this:
local M = {} event = {name = "bubblePop", target = "Runtime"} function M.makeBubble() local rad = math.random( 10,30 ) local r = math.random(0,1) local g = math.random(0,1) local b = math.random(0,1) local newBubble = display.newCircle(0, 0, rad ) newBubble:setFillColor( r,g,b ) -- handler for tapping on the bubble function newBubble:tap(event) -- make bubble a little more transparent with each tap. newBubble.alpha = newBubble.alpha - .3 -- When transparency get's below 0, make bubble disappear if newBubble.alpha \<= 0 then -- update "bubbles popped score" newBubble:dispatchEvent(event ) display.remove( newBubble ) newBubble = nil -- play "pop" sound when the bubble disappears end end newBubble:addEventListener( "tap", newBubble ) return newBubble end return M
I get the a stackoverflow “File: ?” error when I try to fire the bubblePop event. I’ve tried attaching the event to the global (_G) table (which I know is a no-no, but I thought I might as well see if it worked), but then nothing seems to happen at all.
Like I said, this seems like a fairly common use case. There’s probably an obvious solution sand I’m missing it.