迭代法遍歷 table,當Table中含Table時,遞歸調用。打印Table中 K, V值
通過type(arg) 判斷當前類型
table1 = {
name = "Android Developer",
email = "[email protected]",
url = "http://blog.csdn.net/hpccn",
quote = [[
There are
10 types of pepole
who can understand binary.
]],--多行文字
embeddedTab = {
em1 = xx,
x =0,
{x =1, y =2 } -- 再內嵌table
}-- 內嵌table
}
tab = " "
function print_table(t, i)
local indent ="" -- i縮進,當前調用縮進
for j = 0, i do
indent = indent .. tab
end
for k, v in pairs(t) do
if (type(v) == "table") then -- type(v) 當前類型時否table 如果是,則需要遞歸,
print(indent .. "< " .. k .. " is a table />")
print_table(v, i + 1) -- 遞歸調用
print(indent .. "/> end table ".. k .. "/>")
else -- 否則直接輸出當前值
print(indent .. "<" .. k .. "=" .. v.."/>")
end
end
end
print_contents(table1, 0)
輸出結果:
for k,v in pairs(table) do 這樣的遍歷順序並非是table中table的排列順序,而是根據table中key的hash值排序來遍歷的。
與Java中 HashMap, C++中的Map相似。
<name=Android Developer/>
<quote= There ar
10 types of pepole
who can understand binary.
/>
<url=http://blog.csdn.net/hpccn/>
< embeddedTab is a table />
< 1 is a table />
<y=2/>
<x=1/>
/> end table 1/>
<x=0/>
/> end table embeddedTab/>
<[email protected]/>
1 數據類型的判斷: type()
lua語言中的數據類型主要有:nil、number、string、function、table、thread、boolean、userdata。
需要確定一個變量的類型時,可以使用內置函數type獲取,如下:
type(“hello world”); ---->string
type(type); ---->function
type(3.1415); ---->number
type(type(type)); ---->string
2 迭代法
pairs 迭代全部的項
ipairs 迭代以數字做鍵值的項,且從1 開始
for k, v in pairs(t) do