Lua Code:
for i=1, #mydata do
local value = mydata[i]
-- do something with value in sequential array
end
for i, value in ipairs(mydata) do
-- do something with value in sequential array
end
for i, value in pairs(mydata) do
-- do something with value in associative array
end
mydata[#mydata + 1] = newValue -- append sequential
mydata["index"] = newValue -- insert associative
mydata[5] = newValue -- insert associative
table.insert(mydata, 1, newValue) -- prepend (put newValue at mydata[1])
table.insert(mydata, newValue) -- append (put newValue at mydata[#mydata + 1])
To explain what pairs and ipairs do, they essentially just return an index key and value associated with that key in
pairs.
Lua Code:
-- pairs, literally just a wrapper of std next
function pairs (t)
return next, t, nil
end
-- ipairs, does an incremental lookup and stops when the value is nil
local function iter (a, i)
i = i + 1
local v = a[i]
if v then
return i, v
end
end
function ipairs (a)
return iter, a, 0
end
When to use pairs/ipairs?
- pairs - associative arrays, keys are non-numerical or not in sequence starting at 1.
- ipairs - numerically indexed arrays where there are no gaps between [1] and however many elements the table has.