Lua資料結構

2022-05-09 17:08:04 字數 1779 閱讀 8560

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 = ,,,

}-- 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裡面有,

這是什麼意思呢? 這其實就是乙個小table, 定義在了大table之內, 小table的

table名省略了.

最後一行mypolygon[2].x,就是大table裡面小table的訪問方式.

Lua資料結構

1.簡介 lua語言只有一種基本資料結構,那就是table,所有其他資料結構如陣列啦,類啦,都可以由table實現.2.table的下標 例e05.lua arrays mydata mydata 0 foo mydata 1 42 hash tables mydata bar baz iterat...

Lua資料結構。

方法一 local function dotest array for i 1,4 do array i for j 1,4 do array i j 12 end end for i 1,4 dofor j 1,4 do print array i j endend end 方法二 local f...

lua資料結構

1.說明 k v資料結構,k非nil的任意型別 2.賦值local tab 初始化 key 預設 local tab 訪問 tab 1 key 數字 local tab 訪問 tab 60 key 字串 local tab 訪問 tab.aa 1.方法一 local tab 1.增table.ins...