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

Why cant the script find this string in the table?

Asked by 4 years ago

hi i'm new with tables

local testtable = {
subtable1 = {"duck","hat","goose"},
subtable2 = {"truck,","fart","house"}
}

for i, v in pairs(testtable) do
    print(v["fart"])
end

it prints nil(x2)

0
nil means it cant find the thing you are trying to print or there is an error while trying to print it airsoft561 -3 — 4y
0
I know what nil means. The title indicates that I do having said "why cant the script find." ShadyShock 77 — 4y
0
any errors? airsoft561 -3 — 4y
0
Don't do ["fart"], just do print Spjureeedd 385 — 4y

1 answer

Log in to vote
1
Answered by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
4 years ago

When you put v["fart"], you're attempting to check if the index "fart" is within the testtable. That would be the case for a dictionary, so print(testtable["subtable1"]) would work since subtable1 is the key in your dictionary. You have the right idea on using a for loop, but then you'll need another for loop to access the nested tables! Here's how:

local testtable = {
    subtable1 = {"duck", "hat", "goose"}, -- subtable1 is key,  {"duck", "hat", "goose"} is its value
    subtable2 = {"truck", "fart", "house"}
}

for key, value in pairs(testtable) do
    for i, v in pairs(value) do
        if v == "fart" then
            print("Found fart!")
        end
    end
end
Ad

Answer this question