1

I have a multidimensional array:

result = {
  {
    data = {
      language = "English",
      name = "Freak Out",
      list = {
        {
          type = "songs",
          album = "1234"
        }, {
          type = "songs",
          album = "4234"
        }, {
          type = "songs",
          album = "5829"
        }
      }
    }
  }
}

How do I dynamically access the list in this array?

This code is printing first album (1234):

for i, v in pairs(result) do print(v.data.list[1].album) end

I want to print all albums with their type. How do I do this?

1
  • 1
    Is list actually an array, because in the format you specified its an object. Objects cannot be formatted like that. Commented Mar 20, 2019 at 15:08

2 Answers 2

6

result is a list of tables
result[i].data.list is a list of tables.

for _, res in ipairs(result) do
  for _, song in ipairs(res.data.list) do
    print(song.type, song.album)
  end
end

this outputs

songs   1234
songs   4234
songs   5829
Sign up to request clarification or add additional context in comments.

Comments

0

First you need know table have two type in lua.One is hash table, and another is array.In your code. result's member and result.data is a hash table, every element have a string key.result and result.data.list is a array table, all the member in the table have the number key, the default index start by 1.

Second, to traverse the two type table, there are two functions, pairs for hash table and iparis for array table.

print all album in the list(array):

for k, v in ipairs(res.data.list) do
    print(v.type, v.album)
end

3 Comments

Internal implementation using hashing aside, all tables in Lua are dictionaries—there is only one type. A key can be any type and value except nil and NaN. Some of the keys in a table can be positive integers. Some such tables have a sequence. A table with a sequence can have any additional keys. As keys are added or removed, a table can change between having a sequence and not having a sequence. There is still only one type.
Thanks first.But you can see the source code about struct Table.There are a array member and a Node*(list as hash part.)
Yes, it's a struct, not a union. Also, pairs iterates over the entire table, not just what internally is the "hash part". And, ipairs iterates over the positive integer keys from 1 and up to but not including the first nil value, which may or may not be the entirety of internally is the "array part."

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.