Iterating Through an Array - Wrong Order?

Hey everyone,

I've a weird problem. I have a main array that holds items, and within that array I have an additional array for each item (so an array in an array).

When I do a regular loop to go through the items in the main array, it doesn't loop in order. It does a random order instead. I want to loop through the secondary arrays in the order they were inserted into the main array.

Example:

1
2
3
4
5
6
7
mainArray = {
 
item1 = {name = "Hammer" , cost = 100, imgName = "Hammer.png"},
item2 = {name = "Sword" , cost = 500, imgName = "Sword.png"},
item3 = {name = "Gun" , cost = 1000, imgName = "Gun.png"},
 
}

The way you have used tables in the above example is like a dictionary datatype and elements won't be stored in any particular order


There is no guarantee as to the order in which keys will be stored in a table when using dictionaries so the order of retrieval of keys using pairs() is not guaranteed.

-Lua Wiki

I think you should use
 table.insert(mainArray,secondaryTable,1)
or
 mainArray[1]= secondaryTable

just change the declaration slightly as

1
2
3
4
5
mainArray = { 
 {name = "Hammer" , cost = 100, imgName = "Hammer.png"},
 {name = "Sword" , cost = 500, imgName = "Sword.png"},
 {name = "Gun" , cost = 1000, imgName = "Gun.png"},
}

@JayantV

Wow, thanks for that! I would never have realized that. The reason I put item 1, item 2 etc. is so that I can easily do mainArray[nameOfItem].cost or something like that. Otherwise, that method would work perfectly.

Thanks again for the help! :)

You can still do that if you loop though the items like this :

1
2
3
4
5
6
7
8
9
10
11
mainArray = {
 
[1] = {name = "Hammer" , cost = 100, imgName = "Hammer.png"},
[2] = {name = "Sword" , cost = 500, imgName = "Sword.png"},
[3] = {name = "Gun" , cost = 1000, imgName = "Gun.png"},
 
}
 
for i = 1, #mainArray do
    print(nameArray[i].name)
end

@Danny, don't you think that the

1
2
3
4
5
{
[1] = {},
[2] = {},
[3] = {} 
}

@Danny But you still have to access a spot in the array by using mainArray[i].name. If I had about 50 different items, and I wanted to get the stat for particular item, I wouldn't know which index it's stored in. With my code in the first post, I could just do mainArray[rocketLauncher].cost and it would work.

@JayantV Yeah I guess it is redundant, but it makes it easy to take a look at the array and easily tell which index something is stored in (if you have a lot of items).

@Naveen,
you can use *constants*, something like the c enums, which can help you go to the item you need, that way you can use it the way you originally intended to.

cheers,

?:)

views:1084 update:2011/10/19 14:58:09
corona forums © 2003-2011