I try to activate a function (funct02, see below) when objects are “tapped”.
These objects, images in fact, are issued from a random process (funct01) and store in a table.
Funct01 is ok but I can’t activate funct02 when I “tap” objects.
Help would be very much appreciated. What’s wrong?
[lua] local ui = require(“ui”)
local bigTable = { { “s1.png”,“s2.png” } }
local smallTable = { } --store result of random process
local randomImage1 --variable for the first image (random process)
local randomImage2 --for 2nd image
local funct01 = function ( event ) --when btn1 pressed, smallTable is filled
for i = 1, 2 do
local tir1 = math.random( 1, 2 )
smallTable[#smallTable+1] = tir1
end
randomImage1 is equal to the string “s1.png” or “s1.png” and is not a display object. Add the event listener to img1 [import]uid: 12405 topic_id: 5289 reply_id: 17554[/import]
Thanks for quick responses. You’re right… I can see on terminal with a “print” command that randomImage1 is a filename!
But img1:addEventListener (“tap”, funct02) nor img2 doesn’t work… It seems it’s like if they are values table… I hope I missed nothing in your responses.
And a question: img1 and img2 are globale variable, why to declare as local at the top of file (I understand: outside of funct01)? [import]uid: 8970 topic_id: 5289 reply_id: 17607[/import]
I try to do a new example and to simplify to understand what’s wrong…
(summary: I try to generate a random image when a button is pressed; then I want to activate a function when this image is “tapped”).
“img1” is not “add:EventListener” sensitive! If you can point my mistake, thanks.
[lua] local ui = require(“ui”)
local bigTable = { { “s1.png”,“s2.png” } }
local tirage1 = 1 --to initialize with a value
local image1 = bigTable[1] [tirage1] --to initialize
when this first runs you’re creating img1 and adding a tap listener to it. if you were to set alpha to 1 instead of 0, you’ll see your tap function on this button should work
when you then click btn1 to create a *new* img1, my guess is it is overwriting your original img1, and therefore that eventListener no longer exists for img1, since you just changed it to point to a different object.
try this
[lua]local ui = require(“ui”)
local bigTable = { { “s1.png”,“s2.png” } }
local tirage1 = 1 --to initialize with a value
local funct02 = function (event)
print (“OK”)
end
–function to generate a new image
local funct01 = function ( event )
tirage1 = math.random (1,2)
image1 = bigTable[1] [tirage1]
– create a new image
local another_img = display.newImage ( image1 )
another_img.x = math.random(160); another_img.y = math.random(200)
another_img:addEventListener(“tap”,funct02)
end
–Button to activate function01
local btn1 = ui.newButton{
default = “btn1.png”,
over = “btn1_over.png”,
onRelease = funct01
}
btn1.x = 160; btn1.y = 240
[/lua]
what are you actually trying to do though? [import]uid: 6645 topic_id: 5289 reply_id: 17817[/import]