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?
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?
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
This discussion is preserved as it was. New answers, comments, and votes are closed.
5 comments
Why do you need to do "apple = true"?
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.
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
I did not know table.find() existed, thank you for this!
I TOLD YOU!