issue with tables

hi guys…

I contact you cause i’ve a problem with tables.

I’m testing eventListener in a cycle for with table.  when i press the button the value that the simulator print is nill and not t[i].surname.

When i test it without eventListener, the simulator read correctly t[i].surname.

What’s the problem? here i post the codes. 

Thanks for you answers.

-- This code read t[i].surname local t = {} t[1] = {name = "joe", surname = "boed"} t[2] = {name = "joe23", surname = "doe"} t[3] = {name = "joe34", surname = "burk"} for i = 1, #t do print ( t[i].surname ) t[i] = display.newText( t[i].name, 0,0,"Arial",30 ) t[i].x = display.contentCenterX t[i].y = i\*30 end --this code doesn't read t[i].surname local t = {} t[1] = {name = "joe", surname = "boed"} t[2] = {name = "joe23", surname = "doe"} t[3] = {name = "joe34", surname = "burk"} for i = 1, #t do local function listener (event) print ( t[i].surname ) end t[i] = display.newText( t[i].name, 0,0,"Arial",30 ) t[i].x = display.contentCenterX t[i].y = i\*40 t[i]:addEventListener( "tap", listener ) end

When you create your newText object, you are overwriting your ‘t’ entries with the display object.

So t[1], which was a table containing name and surname, becomes a display object. The surname and name fields no longer exist.

This works in example one because you are reading t[1].surname before the text object is created and stored as t[1]. In example two, the object is already created when you try to read t[1].surname.

Just create a new table to hold your text objects. You can store the name and surname on the display object if you want, like this:

[lua]

textObj[i] = display.newText( t[i].name, 0,0,“Arial”,30 )

textObj[i].x = display.contentCenterX

textObj[i].y = i*30

textObj[i].name = t[i].name

textObj[i].surname = t[i].surname

[/lua]

thanks for explain me :) 

Now i understand.  :slight_smile:

When you create your newText object, you are overwriting your ‘t’ entries with the display object.

So t[1], which was a table containing name and surname, becomes a display object. The surname and name fields no longer exist.

This works in example one because you are reading t[1].surname before the text object is created and stored as t[1]. In example two, the object is already created when you try to read t[1].surname.

Just create a new table to hold your text objects. You can store the name and surname on the display object if you want, like this:

[lua]

textObj[i] = display.newText( t[i].name, 0,0,“Arial”,30 )

textObj[i].x = display.contentCenterX

textObj[i].y = i*30

textObj[i].name = t[i].name

textObj[i].surname = t[i].surname

[/lua]

thanks for explain me :) 

Now i understand.  :slight_smile: