#mytable

I found this code on : http://developer.anscamobile.com/forum/2011/12/03/tips-optimization-101

--Table to store the buttons  
local myButtons = {}  
   
myButtons["Pause"] = display.newImage("pause.png")  
myButtons["Pause"].myId = "Pause" --Set the buttons id  
   
myButtons["Shoot"] = display.newImage("shoot.png")  
myButtons["Shoot"].myId = "Shoot" --Set the buttons id  
   
myButtons["Move"] = display.newImage("move.png")  
myButtons["Move"].myId = "Move" --Set the buttons id  
   
myButtons["Retry"] = display.newImage("retry.png")  
myButtons["Retry"].myId = "Retry" --Set the buttons id  
   
--Function to handle our buttons  
local function handleButtons(event)  
 local target = event.target  
   
 --Handle action for each different button  
 if target.myId == "Pause" then  
 --Pause  
 elseif target.myId == "Shoot" then  
 --Shoot  
 elseif target.myId == "Move" then  
 --Move  
 elseif target.myId == "Retry" then  
 ---Retry  
 end  
  
 return true  
end  
   
--Add event listeners for all the buttons  
for i = 1, #myButtons do  
 myButtons[i]:addEventListener("tap", handleButtons)  
end  

i’m using this code… but not working…

so i try to do this :

local prova = {};  
 prova[0] = 2;  
 prova[1] = 3;   
 prova[2] = 3;  
  
 print(#prova); -- output 2 PERFECT!!!  

but if i do this:

 local prova = {};  
 prova[0] = 2;  
 prova[1] = 3;   
 prova["pasd"] = 3;  
  
 print(#prova); -- OUTPUT 1 !!!! NO NO NO...  

So, i like to know if there is a method to use operator # if i use [“letter”] insted of [1]

Thank you :slight_smile:

[import]uid: 153233 topic_id: 27235 reply_id: 327235[/import]

Hello first thing, in lua you cannot initialize a table with an index of 0, all tables start at index of 1.

The Lua # operator only counts entries with integer keys.

However…

For “letters” or as they are known, table “keys” you can grab the tables count/number of entries like so

function tablelength(T)  
 local count = 0  
 for \_ in pairs(T) do count = count + 1 end  
 return count  
end  
  
--Usage  
  
print(tablelength(prova))  

[import]uid: 84637 topic_id: 27235 reply_id: 110713[/import]