遍历lua表格不起作用。

我有以下的 lua 表格:

t = {name="sandy", age="22", major="computerScience"}

我想要遍历它,以下两种方法都不起作用

方法1

function printAssociateTable(t) 
    print("before the loop") 
    for i,v in ipairs(t) do
        print(v) 
    end 
end

方法2

function printAssociateTable2(t) 
    print("before the loop") 
    for k in ipairs(t) do
        print("before the loop")
        print(k.. " is " ..t.k) 
    end 
end

当我调用任何一个方法,他们都会打印 "before the loop",所以问题是程序没有进入循环!

我尝试手动访问表,如果我这样做:

return t.name
=> gives sandy

return t[name]
=> gives nil

return t["name"]
=> gives sandy!

如何遍历我的表格?请注意,这两种方法对于如下的简单数组都可以正常工作:

a={"a","b","c","d"}

但我想要它可以在我的关联数组上工作。

原文链接 https://stackoverflow.com/questions/10678126

点赞
stackoverflow用户622310
stackoverflow用户622310

ipairs 迭代器仅选择带整数键的数组元素。要遍历所有键,您需要使用 pairs,像这样:

function printAssociateTable(t)
  print("before the loop")
  for i,v in pairs(t) do
    print(v)
  end
end
2012-05-20 23:50:44