0

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
1
  • 2
    You're code looks like you're overthinking it. Take out the inner for statement. The info you want is in data.phone. Commented Jul 9, 2020 at 1:06

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your solutions. I prefer the second solution. One question...why the k in phoneNumers[k]?
you can name it whatever you like, but for me k, v (key, value pairs) are more readable.
oh I misunderstood your question, I put k to avoid assigning an index (i) and doing i = i + 1
OK. So the K just assigns the index of the original table to the new table? Am I understanding that correctly? I would have just tried phoneNumbers[]. Would that have not worked?
no that wouldn't have worked, you need an index, see the first example, unless you use table.insert...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.