Table.find not functioning correctly

I am making a function that checks if value names in my profileservice data match with names of values in my folder in serverstorage. Problem is, when i use table.find, it doesnt work and only returns as nil. Any ideas? Also how would i make it so i could find a table value with a instance name?

for i,v in pairs(game.ServerStorage.Items:GetChildren()) do
			local n = table.find(data,v.Name)
			print(n)
			if n == nil then
				print(v.Name.." Is not found in game.ServerStorage.Items")
			end
			if n ~= nil then
				print(v.Name.." has been found")
			end
		end 
		end

data table:

{
		Sword = 0;
	}

thanks in advance!

table.find doesn’t work with dictionaries.
You can directly index a dictionary table in order to find out if the key is present:

local n = data[v.Name]

if n then
  ...
else
  ...
end
2 Likes

I would like to add that dictionaries should be the preferred data structure for storing and then finding large amounts of values, so long as they are supported by what’s storing them.


(someone please correct me if I’m wrong)

The table.find() function has a time complexity of O(n) because it has to look through the entire array, while directly indexing a hashmap (a dictionary) will have on average a constant lookup time of O(1), making it far superior for finding stuff in large data sets. Below is a demonstration of the difference between an array structure and a hashmap structure:

--array method
local array = {
  1,
  'apple',
  true,
  workspace.Part
}
print(table.find(array, workspace.Part) ~= nil) --does the part exist?

--dictionary method
local dict = {
  [1] = true,
  ['apple'] = true,
  [true] = true,
  [workspace.Part] = true,
}
print(dict[workspace.Part] ~= nil) --does the part exist?
1 Like

You’re right, although I’m not sure how exactly Luau implements table.find and direct dictionary indexing, the dictionary indexing indeed has much better performance.

Passing it to a remote/bindable event/function can be done using JSONEncode and JSONDecode functions.

The documentation says that table.find uses linear search, which makes sense because the elements in the array could be anything and can’t always be sorted.

Hashmaps always use a hashing algorithm to serialize objects, and Luau should be no different.

Not always. Only strings and numerical keys are allowed, so anything else such as Instances and Vector3s won’t work.

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