通過例子學(xué)習(xí)Lua(3)—Lua數(shù)據(jù)結(jié)構(gòu)
1.簡介
Lua語言只有一種基本數(shù)據(jù)結(jié)構(gòu), 那就是table, 所有其他數(shù)據(jù)結(jié)構(gòu)如數(shù)組啦、類, 都可以由table實(shí)現(xiàn).
2.table的下標(biāo)
例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
輸出結(jié)果
0=foo
1=42
bar=baz
程序說明
首先定義了一個(gè)table myData={}, 然后用數(shù)字作為下標(biāo)賦了兩個(gè)值給它. 這種定義方法類似于C中的數(shù)組, 但與數(shù)組不同的是, 每個(gè)數(shù)組元素不需要為相同類型,就像本例中一個(gè)為整型, 一個(gè)為字符串.
程序第二部分, 以字符串做為下標(biāo), 又向table內(nèi)增加了一個(gè)元素. 這種table非常像STL里面的map. table下標(biāo)可以為Lua所支持的任意基本類型, 除了nil值以外.
Lua對(duì)Table占用內(nèi)存的處理是自動(dòng)的, 如下面這段代碼
- 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, 只占用一塊內(nèi)存, 當(dāng)執(zhí)行到a = nil時(shí), b仍然指向table,
而當(dāng)執(zhí)行到b=nil時(shí), 因?yàn)闆]有指向table的變量了, 所以Lua會(huì)自動(dòng)釋放table所占內(nèi)存
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)
程序說明
首先建立一個(gè)table, 與上一例不同的是,在table的constructor里面有{x=0,y=0},這是什么意思呢? 這其實(shí)就是一個(gè)小table, 定義在了大table之內(nèi), 小table的table名省略了。
最后一行myPolygon[2].x,就是大table里面小table的訪問方式。
原文鏈接:http://tech.it168.com/j/2008-02-14/200802141314299.shtml