Lua table簡明總結(jié)
一. table
table是lua唯一的數(shù)據(jù)結(jié)構(gòu)。table 是 lua 中最重要的數(shù)據(jù)類型。 table 類似于 python 中的字典。table 只能通過構(gòu)造式來創(chuàng)建。其他語言提供的其他數(shù)據(jù)結(jié)構(gòu)如array、list等等,lua都是通過table來實(shí)現(xiàn)的。table非常實(shí)用,可以用在不同的情景下。最常用的方式就是把table當(dāng)成其他語言的數(shù)組。
實(shí)例1:
mytable = {}
for index = 1, 100 do
mytable[index] = math.random(1,1000)
end
說明:
1). 數(shù)組不必事先定義大小,可動態(tài)增長。
2). 創(chuàng)建包含100個(gè)元素的table,每個(gè)元素隨機(jī)賦1-1000之間的值。
3). 可以通過mytable[x]訪問任意元素,x表示索引。
4). 索引從1開始。
實(shí)例2:
tab = { a = 10, b = 20, c = 30, d = 'www.dhdzp.com' }
print(tab["a"])
說明:
1). table 中的每項(xiàng)要求是 key = value 的形式。
2). key 只能是字符串, 這里的 a, b, c, d 都是字符串,但是不能加上引號。
3). 通過 key 來訪問 table 的值,這時(shí)候, a 必須加上引號。
實(shí)例3:
tab = { 10, s = 'www.dhdzp.com', 11, 12, 13 }
print(tab[1]) = 10
print(tab[2]) = 11
print(tab[3]) = 12
print(tab[4]) = 13
說明:
1). 數(shù)標(biāo)從1開始。
2). 省略key,會自動以1開始編號,并跳過設(shè)置過的key。
二. table函數(shù)
lua提供了許多實(shí)用的內(nèi)建函數(shù)來操作table。
2.1 table.getn(table)
返回table中的元素個(gè)數(shù)。
print(table.getn(tab)) -> 4
2.2 table.insert(table,position,value)
在table中插入一個(gè)新的值,位置參數(shù)可選的,如果沒有指定,會添加table的末尾,否則插入到指定的位置。
table.insert(tab, 2, “hello jb51.net”)
插入”hello jb51.net”到table的第2個(gè)元素的位置,并重新索引。
2.3 table.remove(table,position)
從指定table中刪除并返回一個(gè)元素,如果沒有指定position值,則默認(rèn)刪除最后一個(gè)元素。
print(table.remove(tab,2)) -> hello jb51.net
三. table引用
table不僅可以使用數(shù)字索引,也可以用其他值作為索引值。
tab = ()
tab.website = "www.dhdzp.com"
tab.QQ = "39514058"
tab.a = math.random(1,10)
tab[1] = 11
tab[2] = 22
四. 多維table
在lua中創(chuàng)建多維table非常容易的??梢园讯嗑Stable看做是table的table??梢酝ㄟ^多個(gè)關(guān)鍵字來訪問。
multitab = {}
multitab.name = {}
multitab.author = {}
multitab.name[1] = "QQ qun: 39514058"
multitab.name[2] = "website: http://www.dhdzp.com"
multitab.author[1] = "默北"
multitab.author[2] = "涼白開"
multitab.author[3] = "tonyty163"
五. 遍歷table
pairs()函數(shù)可以遍歷table中的每個(gè)元素。
tab = { 10, s = 'www.dhdzp.com', 11, 12, 13 }
for k, v in pairs(tab) do
print(k, ":", v)
end
輸出:
1 : 10
2 : 11
3 : 12
4 : 13
s : www.dhdzp.com
pairs()函數(shù)遍歷整個(gè)table,即使不知道table長度,并返回索引值和相對應(yīng)的元素值。
相關(guān)文章
分析Lua觀察者模式最佳實(shí)踐之構(gòu)建事件分發(fā)系統(tǒng)
當(dāng)對象間存在一對多關(guān)系時(shí),則使用觀察者模式(Observer Pattern)。比如,當(dāng)一個(gè)對象被修改時(shí),則會自動通知依賴它的對象。觀察者模式屬于行為型模式2021-06-06
Lua腳本實(shí)現(xiàn)遞歸刪除一個(gè)文件夾
這篇文章主要介紹了Lua腳本實(shí)現(xiàn)遞歸刪除一個(gè)文件夾,本文給出了C++和Lua兩個(gè)版本的實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05

