迭代lua表不起作用 [英] iterate over lua table is not working
问题描述
我有以下 lua 表:
I have the following lua table :
t = {name="sandy", age="22", major="computerScience"}
t = {name="sandy", age="22", major="computerScience"}
我想迭代它,下面的两种方法都不起作用
I want to iterate over it, both methods below do NOT work
方法一
function printAssociateTable(t) print("before the loop") for i,v在 ipairs(t) 做打印(v)结束结束
function printAssociateTable(t) print("before the loop") for i,v in ipairs(t) do print(v) end end
方法二
function printAssociateTable2(t) print("before the loop") for k inipairs(t) 做打印(循环之前")print(k.. " is " ..t.k) end end
function printAssociateTable2(t) print("before the loop") for k in ipairs(t) do print("before the loop") print(k.. " is " ..t.k) end end
当我调用任一方法时,它们都会打印在循环之前".所以问题是程序没有进入循环!
when I call either methods, they print "before the loop". so the problem the program is not entering the loop !
我尝试手动访问表,如果我这样做:
i tried to manually access the table, if i do this :
返回t.name=> 给沙质
return t.name => gives sandy
返回 t[name]=> 给出 nil
return t[name] => gives nil
返回 t["name"]=> 给桑迪!
return t["name"] => gives sandy !
如何遍历我的表?请注意,这两种方法都适用于像这样的简单数组
how can i iterate over my table ? kindly note that both methods work well with a simple array like this
a={"a","b","c","d"}
a={"a","b","c","d"}
但我希望它在我的关联数组上工作
but i want it to work on my associative array
推荐答案
ipairs
迭代器仅选择具有整数 键的数组元素.要遍历所有需要 pairs
的键,如下所示:
The ipairs
iterator selects only the array elements with integer keys. To iterate over all keys you require pairs
, like this:
function printAssociateTable(t)
print("before the loop")
for i,v in pairs(t) do
print(v)
end
end
这篇关于迭代lua表不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!