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?

1
  • What happens when you do print(a[1])? Did you try print(a[1][1])? Commented Jul 7, 2014 at 16:48

2 Answers 2

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

1 Comment

I think in this case ipairs is a better choice
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

Comments

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.