Display contents of tables in lua

Neenu picture Neenu · Jan 30, 2017 · Viewed 30.5k times · Source

What I'm trying to do is display the content of table using the following code in 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

The output I got is:

1   table: 0x9a2d8b0
2   table: 0x9a2d110
3   table: 0x9a2cb28

Answer

Oka picture Oka · Jan 30, 2017

To display nested tables you will have to use nested loops.

Also, use ipairs to iterate through array-like tables, and pairs to iterate through record-like tables.

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

Output:

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