当前位置 : 主页 > 网络编程 > lua >

在lua中显示表的内容

来源:互联网 收集:自由互联 发布时间:2021-06-23
我正在尝试做的是使用Lua中的以下代码显示表的内容. local people = { { name = "Fred", address = "16 Long Street", phone = "123456" }, { name = "Wilma", address = "16 Long Street", phone = "123456" }, { name = "Barney", ad
我正在尝试做的是使用Lua中的以下代码显示表的内容.

local people = {
   {
   name = "Fred",
   address = "16 Long Street",
   phone = "123456"
   },

   {
   name = "Wilma",
   address = "16 Long Street",
   phone = "123456"
   },

   {
   name = "Barney",
   address = "17 Long Street",
   phone = "123457"
   }

}
for k, v in pairs(people ) do
    print(k, v)
end

我得到的输出是:

1   table: 0x9a2d8b0
2   table: 0x9a2d110
3   table: 0x9a2cb28
要显示嵌套表,您必须使用嵌套循环.

此外,使用ipairs迭代类似数组的表,使用pairs迭代类似记录的表.

local people = {
   {
       name = "Fred",
       address = "16 Long Street",
       phone = "123456"
   },
   {
       name = "Wilma",
       address = "16 Long Street",
       phone = "123456"
   },
   {
       name = "Barney",
       address = "17 Long Street",
       phone = "123457"
   }
}

for index, data in ipairs(people) do
    print(index)

    for key, value in pairs(data) do
        print('\t', key, value)
    end
end

输出:

1   
        phone   123456          
        name    Fred            
        address 16 Long Street          
2   
        phone   123456          
        name    Wilma           
        address 16 Long Street          
3   
        phone   123457          
        name    Barney          
        address 17 Long Street
网友评论