4

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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Dahknee
  • 591
  • 3
  • 12
  • 28

2 Answers2

4

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
hugomg
  • 68,213
  • 24
  • 160
  • 246
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
3

If you have

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

Then the second element of a will be a[2], the table { "username1", "password1", 1000000, }. If hyou print it it will look similar to table: 0x872690 - its just just how tables are printed in Lua by default. To access the inner fields you just use the same indexing operators. For the first field we do a[2][1], for the second we do a[2][2] and so on.

 for i = 2, #a do
     print(a[i][1], a[i][2], a[i][3])
 end
hugomg
  • 68,213
  • 24
  • 160
  • 246