读书笔记: Programming in Lua, 4th Edition.
> a = {}
> a["x"] = 10
> b = a -- 'b' refers to the same table as 'a'
> b["x"] --> 10
> b["x"] = 20
> a["x"] --> 20
> a = nil -- only 'b' still refers to the table
> b = nil -- no references left to the table
When a program has no more references to a table, the garbage collector will eventually delete the table and reuse its memory.
Table Indices
> a = {} -- empty table
> a.x = 10 -- same as a["x"] = 10
> a.x --> 10 -- same as a["x"]
> a.y --> nil -- same as a["y"]
A common mistake for beginners is to confuse a.x with a[x]. The first form represents a[“x”], that is, a table indexed by the string “x”. The second form is a table indexed by the value of the variable x. See the difference:
> a = {}
> x = "y"
> a[x] = 10 -- put 10 in field "y"
> a[x] --> 10 -- value of field "y"
> a.x --> nil -- value of field "x" (undefined)
> a.y --> 10 -- value of field "y"
> i = 10; j = "10"; k = "+10"
> a = {}
> a[i] = "number key"
> a[j] = "string key"
> a[k] = "another string key"
> a[i] --> number key
> a[j] --> string key
> a[k] --> another string key
> a[tonumber(j)] --> number key
> a[tonumber(k)] --> number key
Table Constructors
days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
print(days[4]) --> Wednesday
opnames = {["+"] = "add", ["-"] = "sub",
["*"] = "mul", ["/"] = "div"}
i = 20; s = "-"
a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s}
print(opnames[s]) --> sub
print(a[22]) --> ---
{x = 0, y = 0} <--> {["x"] = 0, ["y"] = 0}
{"r", "g", "b"} <--> {[1] = "r", [2] = "g", [3] = "b"}
Arrays, Lists and Sequences
To represent a conventional array or a list, we simply use a table with integer keys.
We call such a list without holes a sequence.
Table Traversal
We can traverse all key–value pairs in a table with the pairs iterator:
t = {10, print, x = 12, k = "hi"}
for k, v in pairs(t) do
print(k, v)
end
--> 1 10
--> k hi
--> 2 function: 0x420610
--> x 12
For lists, we can use the ipairs iterator:
t = {10, print, 12, "hi"}
for k, v in ipairs(t) do
print(k, v)
end
--> 1 10
--> 2 function: 0x420610
--> 3 12
--> 4 hi
In this case, Lua trivially ensures the order.
Another way to traverse a sequence is with a numerical for:
t = {10, print, 12, "hi"}
for k = 1, #t do
print(k, t[k])
end
--> 1 10
--> 2 function: 0x420610
--> 3 12
--> 4 hi