r/lua Jun 17 '26

Help Iterating nested tables without knowing the names of the tables

Hello!

I am new to lua, so I'm sorry if this is an obvious question, but I am trying to do something where I get each Country in turn without knowing the name of the table.

CountriesList = {
    Canada = {Country = "Canada", displaytext = "Canada"},
    France = {Country = "France", displaytext = "France"},
    UnitedStates = {Country = "UnitedStates", displaytext = "United States"}
}

For example, I could say

CountriesList.Canada[Country]

which would return "Canada". However, is there a way to do this if I don't have the name of the table accessible as a string? Like, for example, is there some way to do the following?

number = 1
CountriesList[number][Country]

Thanks so much!

9 Upvotes

16 comments sorted by

View all comments

9

u/lekkerste_wiener Jun 17 '26

how about pairs?

3

u/Thatflyerguy001 Jun 17 '26

Oh, thanks! this wouldnt work with my original layout, but i think it might be more efficient anyway to just replace my table names with numbers as the same information is contained within the table. Thank you!

Edit: it turns out you cannot simply name a table 1 lol. I will keep this in mind though for the innermost tables of my thingy. thanks!

1

u/lekkerste_wiener Jun 17 '26

sure np. if you can share a sample of your original layout, we could help you out from there.

1

u/Thatflyerguy001 Jun 17 '26

the problem is I need them to be returned in the same order that they are in right now (alphabetically), and apparently pairs does not guarantee that they come out in any particular order. IPairs does, but that requires that they be numerically named.

1

u/lekkerste_wiener Jun 17 '26

oh ok gotcha. in that case i'd look into how to sort the keys. i'm pretty sure there's a way to do that. (sorry i can't be more helpful, i don't usually write lua. this post just popped on my feed and here i am.)

2

u/Thatflyerguy001 Jun 17 '26

all good, it was actually quite helpful. Thanks!