How do you iterate through an associative array? For example, in python I can do:
dictionary={“one”:1,“two”:2}
for item in dictionary:
print item
Here is my corona example:
local myArray = {
SHAPE1 = {visible = true, image = "image1.png"},
SHAPE2 = {visible = true, image = "image2.png"},
SHAPE3 = {visible = false, image = "image3.png"},
SHAPE4 = {visible = false, image = "image4.png"}
}
[import]uid: 39238 topic_id: 7007 reply_id: 307007[/import]
jmp909
February 22, 2011, 1:53pm
2
[lua]for key,value in pairs(myArray) do
print(key,value, value.image)
end[/lua]
there’s no specific order though [import]uid: 6645 topic_id: 7007 reply_id: 24552[/import]
I just tried that and it didn’t work. [import]uid: 39238 topic_id: 7007 reply_id: 24555[/import]
jmp909
February 22, 2011, 2:06pm
4
go here:
http://www.lua.org/cgi-bin/demo
enter this
[lua]local myArray = {
SHAPE1 = {visible = true, image = “image1.png”},
SHAPE2 = {visible = true, image = “image2.png”},
SHAPE3 = {visible = false, image = “image3.png”},
SHAPE4 = {visible = false, image = “image4.png”}
}
for key,value in pairs(myArray) do
print(key,value, value.image)
end[/lua]
hit run…
you get this
[lua]SHAPE2 table: 0x62eb20 image2.png
SHAPE1 table: 0x62ea70 image1.png
SHAPE3 table: 0x62ebd0 image3.png
SHAPE4 table: 0x62ec80 image4.png[/lua]
what doesnt work exactly?
[import]uid: 6645 topic_id: 7007 reply_id: 24556[/import]
jmp909
February 22, 2011, 2:09pm
5
and for your python example
[lua]dictionary={one=1,two=2}
dictionary[“three”]=3
for key,value in pairs(dictionary) do
print(key,value)
end[/lua]
note there’s no specific order to it though. [import]uid: 6645 topic_id: 7007 reply_id: 24557[/import]
Alright thanks I got it to work. It was saying there was an unknown symbol near the word “for” [import]uid: 39238 topic_id: 7007 reply_id: 24558[/import]
zaphod8
February 22, 2011, 2:42pm
7
Why does it not return the values in the original order? ie
[lua]SHAPE1 table: 0x62ea70 image1.png
SHAPE2 table: 0x62eb20 image2.png
SHAPE3 table: 0x62ebd0 image3.png
SHAPE4 table: 0x62ec80 image4.png[/lua] [import]uid: 22878 topic_id: 7007 reply_id: 24562[/import]
jmp909
February 22, 2011, 11:38pm
8
it just doesn’t
if you need it ordered, use the function on here for instance
http://www.lua.org/pil/19.3.html [import]uid: 6645 topic_id: 7007 reply_id: 24608[/import]
Zarniwoop,
It is like a python dictionary. Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; they are simply unordered.
[import]uid: 13932 topic_id: 7007 reply_id: 24638[/import]