標籤:blog java 使用 strong 資料 os
table類型實現了“關聯陣列”。“關聯陣列”是一種具有特殊索引方式的數組。不僅可以通過認證來索引它,還可以使用字串或其他類型(除了nil)來索引它。table是Lua中主要的資料結構機制(事實也是僅有的),具有強大的功能。基於table可以以一種簡單、統一和高效的方式來表示普通數組、符號表、集合、記錄、隊列和其他資料結構。
table的特性:
- table是一個“關聯陣列”,數組的索引可以是數字或者是字串
- table 的預設初始索引一般以 1 開始
- table 的變數只是一個地址引用,對 table 的操作不會產生資料影響
- table 不會固定長度大小,有新資料插入時間長度度會自動成長
先看table的簡單的例子:
> a={} //空table> k="x"> a[k]=10> print(a[k])10> a["x"]=a["x"]+1 //自增> print(a["x"])11
Lua提供了更簡單的”文法糖“(syntactic sugar)
a.x=10 --print(a["x"]=10)print(a.x) --等於print(a["x"])
table迴圈讀入
for i=1,5 doa[i]=io.read()end
table迴圈輸出
for i=1,#a doprint(a[i])end
#a表示table a最後一個索引
table 的方法函數
1. concat
函數 table.concat 主要用來把表裡的每個元素通過一個分隔字元(separator)串連組合起來,文法如下:
table.concat(table, sep, start, end)
sep、start、end 這三個參數都是可選的,並且順序讀入的,如果沒指定傳入,函數 concat 會採用預設值(分隔字元 sep 的預設值是Null 字元, start 的預設值是 1, end 的預設值是數組部分的總長)去執行。
> tbl = {"one", "two", "three", "four"}> print(table.concat(tbl))onetwothreefour> print(table.concat(tbl, " "))one two three four> print(table.concat(tbl, " ", 2))two three four> print(table.concat(tbl, " ", 2, 3))two three
字元串連還有".."方式
a=a.."two"
2. insert
函數 table.insert 用於向 table 的指定位置(pos)插入一個新元素,文法:
table.insert(table, pos,value)
pos插入位置,可選項
> a={"one","two"}> table.insert(a,"three")> print(table.concat(a," "))one two three
3. remove
文法:
table.remove (tb,pos)
參數 pos 可選,預設為刪除 table 最後一個元素,並且參數 pos 的類型只能是數字 number 類型。
> tb={"one","two","three","four"}> table.remove(tb,1)> print(table.concat(tb," "))two three four> table.remove(tb)> print(table.concat(tb," "))two three
4.maxn
函數 table.maxn 是返回 table 最大的正數索引值,文法:
table.maxn(tb)
>tb={"one","two","three"}> table.maxn(tb)> print(table.maxn(tb))3
5. sort
函數 table.sort 用於對 table 裡的元素作排序操作,文法
table.sort(table,comp)
comp是一個比較函數
>tb={"one","two","three"}> sort_comp = function(a, b) return a > b end> table.sort(tb,sort_comp)> print(table.concat(tb," "))two three one
6. unpack
函數 table.unpack 用於返回 table 裡的元素,文法:
unpack(table, start, end)
參數 start 是開始返回的元素位置,預設是 1,參數 end 是返回最後一個元素的位置,預設是 table 最後一個元素的位置,參數 start、end 都是可選
> a = {"one","two","three"}> print(unpack(a))one two three> print(unpack(a,2))two three> print(unpack(a,2,3))two three
7. pack
函數 table.pack 是擷取一個索引從 1 開始的參數表 table,並會對這個 table 預定義一個欄位 n,表示該表的長度, 文法:
table.pack(···)
該函數常用在擷取傳入函數的參數。
#!/usr/local/bin/luafunction table_pack(...) args = pack(...) print(args.n) tmp={"one","two"} print(tmp.n)endtable_pack("test","arg2","arg3")