Share Your Code

Adding Image and dynamic function from array

Posted by renvis@technowand, Posted on August 17, 2011

Simple code to load image and function to be associated to its event from a table. I hope you will find it useful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
--array with image name and function to be called on click event
local circles = {{"image1","fn1"}, {"image1","fn2"}, {"image1","fn3"}}
 
local x= -30
 
function fn1(self,event) 
  print("Function 1 Called")
end
 
function fn2(self,event) 
  print("Function 2 Called")
end
 
function fn3(self,event) 
  print("Function 3 Called")
end
 
for i=1, #circles do
        x = x +100
                images = display.newImage(circles[i][1]..".png")
                images.x = x 
                images.tag = circles[i][2]
                --getting the function from global name space
                images.touch = _G[circles[i][2]]
                images:addEventListener("touch",images)   
end


Replies

JayantV
User offline. Last seen 1 day 15 hours ago. Offline
Joined: 31 Oct 2009

Technowand, this is good,

1. I personally do not like playing with the _G variable

2. If this was to be used in a black box code, then it would fail as the variable circle has to be hardcoded

think about those

cheers,

?:)

renvis@technowand
User offline. Last seen 6 weeks 12 hours ago. Offline
Joined: 22 Jun 2011

@jayant
I have re written it with out using the global namespace

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
--array with image name and function to be called on click event
local circles = {{"image1","fn1"}, {"image1","fn2"}, {"image1","fn3"}}
local x= -30
local callbacks = {}
 
local function fn1(self,event) 
  print("Function 1 Called")
end
 
local function fn2(self,event) 
  print("Function 2 Called")
end
 
local function fn3(self,event) 
  print("Function 3 Called")
end
 
-- putting the functions in to a table with key as the function name 
callbacks["fn1"] = fn1 
callbacks["fn2"] = fn2 
callbacks["fn3"] = fn3 
 
 
for i=1, #circles do
        x = x +100
                images = display.newImage(circles[i][1]..".png")
                images.x = x 
                images.tag = circles[i][2]
                --getting the function with function name as key from table callbacks
                images.touch = callbacks[circles[i][2]]
                images:addEventListener("touch",images)   
end

thedavebaxter
User offline. Last seen 3 days 3 hours ago. Offline
Joined: 12 Jan 2012

Hi,

Can someone explain (or point me to a explanation) why callbacks[circles[i][2]] works but circles[i][2] doesn't ?

As far as I can see they both hold the same value, which is the name of the function. I don't understand why you need the callbacks table.

Dave