A line to detect if a list contain a specific item

Hello! I know how to detect if a list contain a specific item but I must use check all list items with a index variable. Are there an existing boolean to detect if a list contain a specific item?

e.g.

local function withinTable(tab, val)
	for i, v in pairs(tab) do
		if v == val then
			return i, v
		end
	end
end

local array = {'hi', 'i', 'am', 'an', 'array'}

local index, val = withinTable(array, 'hi')

if index and val then
	print('Value found within table at index', index)
end

I know already make this but are there an existing just a simple boolean to detect if a list contain a specific item?

There are built in functions for tables. You can view the full list here. But you will probably want ot use table.find(table,Value).

Provided you give it a table to search through and a value to attempt to find it will either return the index that value is located at or nil if it didn’t find a matching value.

Because of how Lua works, nil is equal to false and if something exists it is equal to true. So below is some code that works.

testTable = {"a","b","c","d"}

if table.find(testTable,"d") then --If statement only runs if the logic code returns true.
     print("The value exists!")
end

if table.find(testTbale,"e") then
   print("The value exists!") --This won't print
end
1 Like

Why your code work when I search a string but don’t work when I search a Variable?

1 Like