I’m fairly new to corona and I’m trying to wrap my head around how to use classes and event listeners together. I’ve read some things on the topic but I’m not quite getting it.
I’m making something like a board game, where the user can choose a rune by tapping on it, and then tap again to place the rune. This means there are two types of runes in my game, those that are playable and those that have already been played.
I’ve made class to for the runes and there data. It looks like this:
local rune = {} local rune\_mt = {\_index = rune} -- set up image sheet local runeInfo = require("runesSheet") local runeSheet = graphics.newImageSheet( "runes.png", runeInfo:getSheet() ) function rune.new(value, xPos, yPos, isSelectable) -- constuctor local newRune = display.newImageRect(runeSheet, value, 52, 52) newRune.x = xPos newRune.y = yPos newRune.value = value -- this is used both to determine which sprite shows up, but also the value of the rune for comparisson and game logic newRune.isSelectable = isSelectable return setmetatable( newRune, rune\_mt ) end return rune
Now before I start using classes when I just had everything in one messy file, I had an event listeners set up on the playable runes so that when the user tapped on them, they scaled and there value was saved, so that I would know what rune had been chosen. So rune1 was just a imageRect declared locally in my main.lua file. It looked like this and worked:
local currentChoice local function runeTapped(event) local thisRune = event.target if (currentChoice) then transition.scaleTo( currentChoice, {xScale = 1, yScale = 1, time = 100} ) end transition.scaleTo( thisRune, {xScale = 1.2, yScale = 1.2, time = 100} ) currentChoice = thisRune return true end rune1:addEventListener( "tap", runeTapped )
But now that rune1 isn’t just a local variable, but a class, I get the error that addEventLister has a nil value. Okay, that makes sense, I haven’t declared addEventListener inside of rune.lua
What I can’t seem to grasp is this. I want the runeTapped event to happen in my main.lua file, because I need to be able to effect the currentChoice variable so that I know if there is an active selection by the player and what that is, for the next tap, which could be on an object of a different class.
My first thought was to add something like this to my rune class:
if (self.isPlayable) then self:addEventListener( "tap", listener ) end
but if I do that, how do I write the listener function so that it passes a value back into main.lua? Or am I going about this the wrong way?