Is there something similar with FindFirstChild() but work on table?

so you see the topic name, I will give an example if you dont understand.

Folder:FindFirstChild("Something") --return nil if the object isnt there
Table.Something --break the script entirely if the value isnt there
1 Like

table.find for arrays and a manual for loop for dictionaries.

I already look into some table.find but i dont quite understand yet, could you give me an example?

1 Like

For that, you need to understand that there are two types of tables: Arrays and Dictionaries.

local MyArray = {11, 22, 'abc'} 
print(MyArray) 

will print:

    [1] = 11,
    [2] = 22,
    [3] = "abc"
MyArrayId = table.find(MyArray, 'abc')
print(MyArrayId) --<< will print '3'
2 Likes

But what if the value is different but the name of that stay the same?

local Table = {a = 1; b = 2; c = 3;}
-- is there a way to check if that value exist using only the name? (a, b, c)
1 Like

Have you tested this? Dot operator works as FindFirstChild, returns nil if index doesn’t exist; it will just mark a warn, but instead you can use [] to index.

local t = { 
	["foo"] = 1;
}

local bar = t["bar"] -- nil

print(bar) -- nil
2 Likes

This is called a dictionary and to use something similar to FindFirstChild you can do this

local value = Table[key]

if it exists, it will return the value

local value = Table["a"]
print(value)		-- 1

if not, it will return nil

local value = Table["d"]
print(value)		-- nil

also, if you want to apply the recursion of FindFirstChild, you can make the function that check the table loop through the subtables, something like that

local function RecursionFind(Table, Key:string)
	--		Check main table			--
	if Table[Key] then	return Table[Key]	end
	
	--		Check subtables			--
	for k, v in pairs(Table) do
		if type(v) ~= "table" then	continue	end
		local Find = RecursionFind(v, Key)
		if Find then	return Find		end
	end
end

local Table = {
	A = {
		a = 1,
		b = 1,
		c = 1,
	},
	B = {
		d = 1,
		e = 1,
		f = 1,
	},
}
print(RecursionFind(Table, "a"))		-- 1
print(RecursionFind(Table, "nope"))		-- nil
4 Likes

Are you sure Table.Something breaks the script? I just tried it on the Lua interpreter and it just returns nil (no error)

I’ll have to try it in Studio I guess.

Also, in that example, if i try to print(Table[“d”]) , it just prints nil, no error.

local Table = {a = 1; b = 2; c = 3;}

print(Table["notExist"])
print(Table.Tacos)
print(Table.b)

OUTPUT:
nil
nil
2

1 Like