Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Find something specific in a table?

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

✓ Accepted answer

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

5 comments

0

Why do you need to do "apple = true"?

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.

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

0

I did not know table.find() existed, thank you for this!

0

I TOLD YOU!

This discussion is preserved as it was. New answers, comments, and votes are closed.