In Lua there are two types of tables: indexed by a number and indexed by a string or key. Lets talk about the first type first.
Here you have an table like:
local numericTable = {} numericTable[1] = "Hello" numericTable[2] = "World" numericTable[3] = "Welcome" numericTable[4] = "to" numericTable[5] = "Corona SDK"
or you could have defined it as:
local numericTable = { "Hello", "World", "Welcome", "to", "CoronaSDK" }
Both are the same. Each value will have a numeric index ranging from 1 to 5 since there are five entries.
Most people would loop over this with a simple ‘for’ loop using the # operator to get the number of entries in the table:
for i = 1, #numericTable do print( i, numericTable[i] ) end
This is great as long as the keys are actually in a numeric sequence. But lets say you deleted one of the items from the table or for some reason there is a hole in the table such as:
local numericTable = {} numericTable[1] = "Hello" numericTable[2] = "World" numericTable[3] = "Welcome" numericTable[10] = "to" numericTable[11] = "Corona SDK"
In this case, the # operator will return three since the table is not in sequential order. Here you can use ipairs to iterate over the entire table.
for i, v in ipairs( numericTable ) do print(i, v) end
Both will now produce the same output. In this case i, is the index into the table, v holds the value of numericTable[i].
Now tables indexed with string values are not guaranteed to be in any order and you can’t use a for i = 1, #tablesize to loop over the table. Given this table:
local city = { name = "Key West", state = "Florida", postalCode = "33040", latitude="24.5", latitude = "-81.8" }
If you want to iterate over this you will use pairs():
for k, v in pairs( city ) do print( k, v ) end
So for this run, k will print things like: “name”, “state”, “postalCode”, etc. v will hold the values of those entries: “Key West”, “Florida”, “33040” etc.
Hope this helps explain the difference.
As a side note, the variables i, k and v in the examples above are in effect “local” to the inside of the loop only. Once the loop finishes, the values that are held in i, k and v will return to any previous definition.
Rob