一、基本列印table
--定義一個table
local myTable = {key1 = "value1", key2 = "value2", key3 = "value3"}
--列印table
print(myTable)
--輸出:table: 0x7f99f0404670
默認情況下,通過print列印出來的table僅顯示它在內存中的地址。需要通過其他方式將table內容列印出來。
二、使用pairs函數列印table
local myTable = {key1 = "value1", key2 = "value2", key3 = "value3"}
for key, value in pairs(myTable) do
print(key, value)
end
--輸出:
--key1 value1
--key2 value2
--key3 value3
使用pairs函數可以遍歷table中的所有元素,輸出每個元素對應的key和value。
三、使用ipairs函數列印數組型table
local myTable = {"value1", "value2", "value3"}
for index, value in ipairs(myTable) do
print(index, value)
end
--輸出:
--1 value1
--2 value2
--3 value3
使用ipairs函數逐一列印一個數組型table中的元素。注意:ipairs只輸出連續下標的元素。
四、使用table.concat函數列印table
local myTable = {"value1", "value2", "value3"}
local str = table.concat(myTable, ", ")
print(str)
--輸出:"value1, value2, value3"
如果需要將table中的元素拼接成一個字元串,可以使用table.concat函數。
五、美化table列印結果
local myTable = {
key1 = "value1",
key2 = "value2",
key3 = {
subkey1 = "subvalue1",
subkey2 = "subvalue2"
}
}
function printTable(table, level)
level = level or 1
local indent = ""
for i = 1, level do
indent = indent.." "
end
if level > 1 then
print(indent.."{")
end
for k, v in pairs(table) do
if type(v) == "table" then
print(indent..k.." = {")
printTable(v, level + 1)
print(indent.."},")
else
local content = string.format("%s%s = %s,", indent, tostring(k), tostring(v))
print(content)
end
end
if level > 1 then
print(indent.."}")
end
end
printTable(myTable)
--輸出:
--{
-- key1 = value1,
-- key2 = value2,
-- key3 = {
-- subkey1 = subvalue1,
-- subkey2 = subvalue2,
-- },
--}
美化table列印結果可以使輸出更易讀。可以自定義一個函數,遞歸調用列印table中的所有元素,並加入縮進。
總結
在Lua中,可以通過多種方式列印table。通常使用pairs函數遍歷table中的元素,使用ipairs函數遍曆數組型table中的元素。如果需要將table中的元素拼接成一個字元串,可以使用table.concat函數。如果需要美化table列印結果,可以自定義一個遞歸函數。
原創文章,作者:VGNWU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/333388.html
微信掃一掃
支付寶掃一掃