Array = indexed table = table where the keys are sequential integers beginning with 1.
Dictionary = hash table = table where the keys are anything else.
Unlike some programming languages, Lua uses the same data structure -- the table -- for both paradigms.
This is an array:
Code:
local t = {
"apple",
"banana",
"cherry",
}
This is also an array, and is identical to the above:
Code:
local t = {
[1] = "apple",
[2] = "banana",
[3] = "cherry",
}
The
ipairs function will operate identically on both tables:
Code:
for i, v in ipairs(t) do print(i, v) end
1 apple
2 banana
3 cherry
|
However, if the indices are not sequential, like this:
Code:
local t = {
[1] = "apple",
[2] = "banana",
[3] = "cherry",
[7] = "grape",
[13] = "mango",
}
Then
ipairs will only iterate over the indices that begin at 1 and increment sequentially:
Code:
for i, v in ipairs(t) do print(i, v) end
1 apple
2 banana
3 cherry
|
Basically, it will act as if the other values aren't in the table.
You can also use
pairs on an array, and it will return all the values, including the ones that
ipairs skips because they aren't sequential, but it returns them in an undefined order, which basically means random:
Code:
for k, v in ipairs(t) do print(k, v) end
3 cherry
13 mango
7 grape
1 apple
2 banana
|
You can also mix tables, like this:
Code:
local t = {
"apple",
"banana",
[3] = "cherry",
[7] = "grape",
["foo"] = "bar",
["num"] = 5,
}
In this case,
ipairs will still iterate over the sequential indexed values, beginning with 1:
Code:
for i, v in ipairs(t) do print(i, v) end
1 apple
2 banana
3 cherry
|
... and
pairs will iterate over all of the key/value pairs, including the indexed ones (keys are sequential integers counting up from 1), in undefined order:
Code:
for k, v in ipairs(t) do print(k, v) end
foo bar
2 banana
3 cherry
num 5
7 grape
1 apple
|
If you are using an array, it is
slightly faster to avoid
ipairs and simply iterate through the table this way:
Code:
for i = 1, #t do print(i, t[i]) end
1 apple
2 banana
3 cherry
|
... but it's not really significant, so if you feel that
ipairs is easier for you as a programmer to read and understand, feel free to use it.
As for which type of table structure you use, that depends on what kind of data you want to store, and how you want to use it. Without knowing that, I can't make any useful suggestions.