1. Introduction
Lua has only one basic data structure, that is, table. All other data structures, such as arrays,
Can be implemented by table.
2. Table subscript
Example e05.lua
-- Arrays myData = {} myData[0] = “foo” myData[1] = 42 -- Hash tables myData[“bar”] = “baz” -- Iterate through the -- structure for key, value in myData do print(key .. “=“ .. value) end
Output result
0 = foo
1 = 42
Bar = Baz
Program description
First define a table mydata = {}, and then use a number as the subscript to assign two values to it. this definition method is similar to the array in C, but unlike the array, each array element does not need to be of the same type, just as one in this example is an integer and the other is a string.
The second part of the program uses the string as the subscript and adds an element to the table. this table is very similar to the map in STL. the table subscript can be any basic type supported by Lua, except for the nil value.
Lua automatically processes table memory usage, as shown in the following code:
a = {} a["x"] = 10 b = a -- `b' refers to the same table as `a' print(b["x"]) --> 10 b["x"] = 20 print(a["x"]) --> 20 a = nil -- now only `b' still refers to the table b = nil -- now there are no references left to the table
Both B and a point to the same table and only occupy one piece of memory. When a = NIL is executed, B still points to table,
When B = NIL is executed, Lua Automatically releases the memory occupied by the table because it does not point to the table variable.
3. Table nesting
Table can also be nested, as shown in the following example.
Example e06.lua
-- Table ‘constructor’ myPolygon = { color=“blue”, thickness=2, npoints=4; {x=0, y=0}, {x=-10, y=0}, {x=-5, y=4}, {x=0, y=4} } -- Print the color print(myPolygon[“color”]) -- Print it again using dot -- notation print(myPolygon.color) -- The points are accessible -- in myPolygon[1] to myPolygon[4] -- Print the second point’s x -- coordinate print(myPolygon[2].x)
Program description
First, create a table. Different from the previous example, {x = 0, y = 0} exists in the table constructor. What does this mean? This is actually a small table, defined within a large table, and the table name of the small table is omitted.
The last line of mypolygon [2]. X is the access method for small tables in large tables.
1