Tables are essentially associative arrays which can have keys and values of any type. They are incredibly flexible and are the only datastructure in lua.
x = 5
a = {} -- empty table
b = { key = 5, anotherKey = 10} -- strings as keys
-- variables and literals as keys
c = { [x] = b, ["strings"] = 10, [34] = 10, [b] = x }
-- assignment
a[1] = 20
a["foo"] = 50
a[x] = "bar"
-- retrieval
print(b["key"]) -- 5
print(c["string"]) -- 10
print(c[34]) -- 10
print(c[b]) -- 5
printing and referencing
A table variable is a reference to a memory location and thus when you print it out you'll simply print it's memory location. Normally printing a table involved looping over it and printing it's items:
local tbl = {"This", 2, 9.9, true}
for i = 1, #tbl do
print(tbl[i])
end
looping
You can loop manually or with pairs or ipairs:
local tbl = {1, 3, 5, 7, 9}
for k, v in pairs(tbl) do
print(tbl[i])
end
creating
Curly brackets are used to create tables. You can use any kind of expression as a key as long as it's surrounded by square brackets. If the key is to be a string you do not need brackets or qoutes.
syntactic sugar
t = { foo = 1, bar = 2 }
print(t.foo) -- 1
t.bar = 3
This makes using tables much more pleasing. For example, to use sqrt from the
standard math library we can write math.sqrt(x) instead of math["sqrt"](x).
"arrays"
If you do not specify a key when creating a table they will be automatically asigned indices starting at 1.
a = { 11, 22, "foo", "bar" }
a[3] = "foooo"
print(a[1]) -- 11
print(a[3]) -- foooo
-- # is used to get the length of a table
print(#a) -- 4
table module
If you're working with tables as arrays then the table module, part of the
standard library, will help. Here's an example of some of the functions:
t = { 24, 25, 8, 13, 1, 40 }
table.insert(t, 50) -- inserts 50 at the end
table.insert(t, 3, 89) -- inserts 89 at index 3
table.remove(t, 2) -- removes item at index 2
table.sort(t) -- sort via the < operator