How to know if a specific thing is in a table

  1. I want to know how to detect if something is in a table.

For example:

local table = {"1", "2"}

I want to know if it has a specific thing inside like if I wanted to find 1. Or If I wanted to find a player or something like that.

2 Likes
if table.find(table, "1") then

use table.find. example:

local YourTable = {"1", "2"}

if table.find(YourTable, "1") then
    print("Found!")
else
    print("Not Found!")
end

Also keep in mind you shouldn’t define a variable with the name “table” because that would override the table library.

1 Like

How would I find something inside of a table inside of another table for example?

local Table = {
	["anotherTable"] = {
		"1", "2"
	}
}

Try this:

local Table = {
	["anotherTable"] = {
		"1", "2"
	}
}

if table.find(Table["anotherTable"], "1") then
    print("Found!")
end
1 Like

and if you dont know which table its in, you could do something like

for _, v in pairs(Table) do
 if table.find(v, "1") then
  print("Found!")
  break
end

(untested so it might have some stupid mistakes)

1 Like

It’s just a good idea to check if the value is a table using typeof(v) == "table":

-- Whole Code
for _, v in pairs(Table) do
 if typeof(v) == "table" and table.find(v, "1") then
  print("Found!")
  break
end
3 Likes

What if your trying to find something specific and this is your table

local Table = {
	["1"] = {
		"1", "2"
	},
	["2"] = {
		"1", "2"
	}
}

We can see this is a dictionary and not an array, hence using table.find() wouldnd work.

Lets say you want to get the “2” from the first key-value:

print(Table["1"](2))-- should print 2 since each key in the dictionary has a table value, we can get the value from that table by using its index
1 Like

You would have to use recursion and check the value type of the current level being iterated. And you would need a concrete method to identify the required table/value to return successfully from a possibly multi nested function.

It should still work, does it not?

Never mind, it is a dictionary, we would do recursion

function loop(t : {}, val : any, depth : number)
	if depth == 0 then
		return nil
	end
	
	for k, v in pairs(t) do
		if v == val then
			return true
		end
		
		if typeof(v) == "table" then
			local res = loop(v, val, depth - 1)
			
			if res then
				return true
			end
		end
	end
end

loop(Table, val, -1) -- -1 goes forever

(not tested, but should work.)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.