Super simple question: How to pass parameters with event listeners

Hey there, still getting used to Corona/Lua and this problem’s been driving me crazy. I have two buttons with event listeners that goto the function “GainMoney”. I would like button1 to pass the integer “1” but button2 to pass the integer “10”. What would be the best way to do this?

I intend to create Money and Button objects by emulating classes in LUA, would this be a bad idea?

Other tips/recommendations welcome, thanks!

Here’s some example code:

local function gainmoney(event) money = money + --event.money displaymoney.text = "You have $"..money return true end function scene:create( event ) beg = widget.newButton{ label = "Beg for Money", defaultFile = "button.png", width = 154, height = 40, onRelease = gainmoney -- send event.money=1 } work = widget.newButton{ label = "Work for money", defaultFile = "button.png", width = 154, height = 40, onRelease = gainmoney -- send event.money=10 }

With a function like that, I wouldn’t necessarily include any arguments, but I might go with button id’s instead.

However, the way how you’d pass arguments with those button listeners would be to add functions there instead of a reference to one, i.e.

onRelease = function( event ) gainmoney( event, 10 ) end

This way, whenever that button is released, it will call a function which contains a call for your gainmoney function in a way that you can pass arguments in.

 

That looks like just the code I’m looking for Spyric, thanks! How would I do it with button id’s though? I wouldn’t want to have an if statement in gainmoney for every button, or were you meaning like a table connecting button id’s to their income values?

The final project will have many buttons.

Lua is smart enough to know when your string is also a number so you can directly add or subtract such strings from other numbers. I’d go with something like:

local widget = require("widget") local currentMoney = 100 local function adjustMoney( event ) currentMoney = currentMoney + event.target.id print( currentMoney ) return true end local button = widget.newButton({ shape = "rect", id = "-10", -- subtracts 10 per release x = 100, y = 100, width = 100, height = 100, onRelease = adjustMoney })

That’s awesome Spyric! I think both those methods will come in very useful :slight_smile: