Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What can I do to print out content from a table inside another table and how can I do it?

Asked by 4 years ago
Edited 4 years ago

Hello! I have a table for a project I'm working on. I am trying to read the data inside the table that has contents. If you want to do print(tablename[1]) for a table that's inside another table, you get "nil" in your output. Any solutions appreciated!

shorturl.at/inM06

0
tbl1[index1][index2] theking48989987 2147 — 4y

1 answer

Log in to vote
1
Answered by
royaltoe 5144 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

There's a couple ways of doing this:

Option #1:

myTable = {
    {"Dogs", "Cats", "Bunnies"}, 
    {2,3,10}
}

print(myTable[1]) --prints the first table's pointer
print(myTable[1][2]) --print's cats inside of table 1

--loops through all the tables and prints out their values 
for index, innerTable in ipairs(myTable)do
    print(innerTable, " ", index) --prints which table we're looking at
    for itemIndex, item in ipairs(innerTable)do
        print(item, " ", itemIndex) 
    end
end

Option #2:

myTable = {
    Animals = {"Dogs", "Cats", "Bunnies"}, 
    SpecialNumbers = {2,3,10}
}

--This table has no indecies, so you cannot do "print(myTable[1])", but you can instead do


for i, v in ipairs(myTable.Animals)do
    print(v)
end

for i, v in ipairs(myTable.SpecialNumbers)do
    print(v)
end

Option #1 is nice when you want to loop through everything in the table, which is rarely the case when it comes to having tables inside of tables.

Option #2 is nice because instead of looping, you can instantly get the table inside myTable without any added steps, which is a lot quicker when you have a big game with a lot of tables.

Ad

Answer this question