Search code examples
luaiterationlua-tablenested-table

Lua - Getting values from nested tables


Okay so I have been searching everywhere for this, but nowhere has the answer.

I have a nested table (an example):

{
  {
    "Username",
    "Password",
    "Balance",
  },
  {
    "username1",
    "password1",
    1000000,
  },
  {
    "username2",
    "password2",
    1000000,
  },
}

The thing is I can't iterate a loop to view these tables, nor get values from the tables. None nested tables can be accessed easily like:

print(a[1])

How do I loop them and get values from them?


Solution

  • Use pairs or ipairs to iterate over the table:

    local t = {
      {
        "Username",
        "Password",
        "Balance",
      },
      {
        "username1",
        "password1",
        1000000,
      },
      {
        "username2",
        "password2",
        1000000,
      },
    }
    
    for _, v in ipairs(t) do
      print(v[1], v[2],v[3])
    end
    

    will print:

    Username    Password    Balance
    username1   password1   1000000
    username2   password2   1000000