Lua中遍历数组和table的4种方法
方法一,可以用for来遍历:
代码如下:
do table_week = { "w", "e", "r", "t", "y", "u", "i", } for i = 1, #table_week do print(table_week[i]) end end #后面接一个数组或者tabe来遍历它,i是该table或者数组的起始下标。
方法2:
代码如下:
do table_week = { "w", "e", "r", "t", "y", "u", "i", } for i, v in pairs(table_week) do print(i) end end
这种是采用迭代器的方式遍历的,i为下标,v为table或者数组的值。
方式3:
代码如下:
do table_week = { "w", "e", "r", "t", "y", "u", "i", } for i in pairs(table_week) do print(i); end end
i为table或者数组的下标。
方式4:
代码如下:
do table_view = { "w", "e", "r", color1 = "red", color2 = "blue", {"a1", "a2", "a3"}, {"b1", "b2", "b3"}, {"c1", "c2", "c3"}, } for i, v in pairs(table_view) do if type(v) == "table" then for new_table_index, new_table_value in pairs(v) do print(new_table_value) end else print(v) end end end
注:type(v)
功能:返回参数的类型名("nil","number", "string", "boolean", "table", "function", "thread", "userdata")
相关推荐
Masimaro 2020-06-14
kaixinfelix 2020-10-04
liuyang000 2020-09-25
kikaylee 2020-11-11
nongfusanquan0 2020-09-23
aanndd 2020-08-12
Tips 2020-08-08
waitwolf 2020-07-30
81264454 2020-07-17
shenxiuwen 2020-07-05
roseying 2020-07-04
清溪算法君老号 2020-06-27
OldBowl 2020-06-26
dugujiujian 2020-06-25
oXiaoChong 2020-06-20
晓杰0 2020-06-14
vincen 2020-06-12
Jasmineyaoyao 2020-06-08