1.簡介
Lua語言只有一種基本數據結構, 那就是table, 所有其他數據結構如數組啦,
類啦, 都可以由table實現.
2.table的下標
例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
輸出結果
0=foo
1=42
bar=baz
程序說明
首先定義了一個table myData={}, 然后用數字作為下標賦了兩個值給它. 這種
定義方法類似于C中的數組, 但與數組不同的是, 每個數組元素不需要為相同類型,
就像本例中一個為整型, 一個為字符串.
程序第二部分, 以字符串做為下標, 又向table內增加了一個元素. 這種table非常
像STL里面的map. table下標可以為Lua所支持的任意基本類型, 除了nil值以外.
Lua對Table占用內存的處理是自動的, 如下面這段代碼
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
b和a都指向相同的table, 只占用一塊內存, 當執行到a = nil時, b仍然指向table,
而當執行到b=nil時, 因為沒有指向table的變量了, 所以Lua會自動釋放table所占內存
3.Table的嵌套
Table的使用還可以嵌套,如下例
例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)
程序說明
首先建立一個table, 與上一例不同的是,在table的constructor里面有{x=0,y=0},
這是什么意思呢? 這其實就是一個小table, 定義在了大table之內, 小table的
table名省略了.
最后一行myPolygon[2].x,就是大table里面小table的訪問方式.
文章來源于領測軟件測試網 http://www.kjueaiud.com/