XenPanda
XenPanda

Reputation: 137

Lua, insert value from loop into new table

I am trying to figure out how to loop through a LUA table and take the results of a field and enter them into a new table. In the sample code below I would like to get the phone value from each record and insert it into the new table phoneNumbers. I have tried several ways of doing this and basically I keep getting a table with no data.

I am not sure what I am missing, but I feel it has something to do with value.phone. Any help is appreciated!

local phoneNumbers = {}
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
            for key, value in pairs(data) do
        --print('\t', key, value)
        table.insert(phoneNumbers, 1, value.phone)
        --phoneNumbers[1] = value.phone
      end
    end

Upvotes: 0

Views: 2065

Answers (1)

mourad
mourad

Reputation: 687

As per the comment, you can do:

for i = 1, #people do
    phoneNumbers[i] = people[i].phone
end

-- test to see the result
for i = 1, #phoneNumbers do
    print(phoneNumbers[i])
end

Or this also works:

for k, v in pairs(people) do
    phoneNumbers[k] = v.phone
end

-- test to see the result
for k, v in pairs(phoneNumbers) do
    print(k, v)
end

Upvotes: 1

Related Questions