表格是唯一的數(shù)據(jù)結(jié)構(gòu)中Lua可以幫助我們創(chuàng)造出不同的類(lèi)型,如數(shù)組和字典。 Lua使用關(guān)聯(lián)數(shù)組和可不僅數(shù)字,但也有不同的零字符串索引。表格都沒(méi)有固定的大小,并根據(jù)需要可以增長(zhǎng)。
Lua采用的所有陳述,包括包裝的代表性表。當(dāng)我們?cè)L問(wèn)一個(gè)方法的字符串。格式,這意味著,我們正在訪(fǎng)問(wèn)的格式化功能的字符串封裝。
表示和用法
表稱(chēng)為對(duì)象和它們既不值,也沒(méi)有變。 Lua使用構(gòu)造函數(shù)表達(dá)式{}創(chuàng)建一個(gè)空表。它是要知道,有保存表的參考和表本身的變量之間沒(méi)有固定的關(guān)系。
代碼如下:--sample table initialization
mytable = {}
--simple table value assignment
mytable[1]= "Lua"
--removing reference
mytable = nil
-- lua garbage collection will take care of releasing memory
當(dāng)我們有一個(gè)表與集合的元素,如果我們將其指定為b,a和b都指向相同的內(nèi)存。沒(méi)有單獨(dú)的內(nèi)存單獨(dú)分配對(duì)b。當(dāng)設(shè)置為無(wú),表將仍然可以訪(fǎng)問(wèn)到b。當(dāng)沒(méi)有引用表,然后在Lua垃圾收集需要清理過(guò)程,使這些未引用的內(nèi)存再次被重用。
一個(gè)例子如下所示用于說(shuō)明表的上述特征。
代碼如下:-- Simple empty table
mytable = {}
print("Type of mytable is ",type(mytable))
mytable[1]= "Lua"
mytable["wow"] = "Tutorial"
print("mytable Element at index 1 is ", mytable[1])
print("mytable Element at index wow is ", mytable["wow"])
-- alternatetable and mytable refers to same table
alternatetable = mytable
print("alternatetable Element at index 1 is ", alternatetable[1])
print("mytable Element at index wow is ", alternatetable["wow"])
alternatetable["wow"] = "I changed it"
print("mytable Element at index wow is ", mytable["wow"])
-- only variable released and and not table
alternatetable = nil
print("alternatetable is ", alternatetable)
-- mytable is still accessible
print("mytable Element at index wow is ", mytable["wow"])
mytable = nil
print("mytable is ", mytable)
當(dāng)我們運(yùn)行上面的程序,會(huì)得到下面的輸出
代碼如下:Type of mytable is table
mytable Element at index 1 is Lua
mytable Element at index wow is Tutorial
alternatetable Element at index 1 is Lua
mytable Element at index wow is Tutorial
mytable Element at index wow is I changed it
alternatetable is nil
mytable Element at index wow is I changed it
mytable is nil
表操作
在對(duì)表操作內(nèi)置函數(shù)和它們被列于下表中。

讓我們看看上面的函數(shù)一些例子。
表串聯(lián)
我們可以使用concat函數(shù)來(lái)連接,如下所示的兩個(gè)表。
代碼如下:fruits = {"banana","orange","apple"}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注