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

Find something specific in a table?

Asked by
6zk8 95
4 years ago

If I made a list of letters, how would I check to see if another letter is in the table?

local fruitTable = {"apple", "banana", "pear", "orange"}

I have fruit called Peach, how would I check to see if it is in fruitTable?

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

There are a few ways.

The best way is to make a dictionary;

local fruitTable = {
    apple = true,
    banana = "Test",
    pear = { 1, 2, 3 },
    orange = false
}

print(fruitTable["apple"]); -- true
print(fruitTable["pineapple"]); -- nil
print(fruitTable["orange"]); -- false
print(fruitTable["banana"]); -- "Test"
print(fruitTable["pear"][1]]); -- 1
print(fruitTable["pear"][2]]); -- 2
print(fruitTable["pear"][3]); -- 3

or to use a function:

function tableFind(Table, toFind)
local found = false;
    if typeof(Table) == "table" then
        for i,v in pairs(Table) do
            if(v == toFind) then 
                found = true 
            end;
        end
        return found;
    else
        return "First parameter has to be a table.";
    end
end
0
Why do you need to do "apple = true"? 6zk8 95 — 4y
0
That's how a dictionary works. You can assign something to something else. So I can assign a table to a value. I'll update my example to provide some more examples. GeneratedScript 740 — 4y
0
table.find() can also work if you want to shorten your code, although I'm unsure of how it would work with dictionaries : https://developer.roblox.com/en-us/api-reference/lua-docs/table User#20279 0 — 4y
0
I did not know table.find() existed, thank you for this! GeneratedScript 740 — 4y
0
I TOLD YOU! 6zk8 95 — 4y
Ad

Answer this question