How do I check how many things are inside of a dictionary?

You can write your topic however you want, but you need to answer these questions:

  1. I want to check how many things are inside of a shared table/variable that is a table. Keep it simple and clear!

  2. I’ve tried using # to check the amount of things inside the table, but it didn’t work since it’s a dictionary, I also thought of just making a variable and looping through the table and adding +1 to the variable for every loop, but for what I’am doing this will cause a lot of loops happening at once, and it’s also on the server, meaning it’ll be worse

local dictionary = {
["Value1"] = 5,
["Value2"] = 10,
}

print(#dictionary) -- prints 0

Looping over the keys and counting them is the only way to get the length of a dictionary. The # symbol does not work on dictionaries, only arrays.

local dictionary = {
	["Value1"] = 5,
	["Value2"] = 10,
}
local count = 0
for _, _ in dictionary do
	count += 1
end
print(count) -- prints 2
1 Like

This will be running basically every task.wait() on the server, so it’ll be horrible for performance. Is there a better method?

try

local num = #yourDictionaryHere

Im not 100% sure it works but its worth a shot, if not use what @ahsanmoin05 said cause there really isnt any other way

This won’t work, # only works on arrays

It’s not horrible for performance, even on task.wait() this is has linear time complexity.

Even with a large dictionary it around ~0.000008 seconds to do this operation. It’s completely fine even in a large loop. It’s optimized in the Lua JIT compiler.
RobloxStudioBeta_OGTvZd7QgC

Yeah I thought so, well in that case do what @ahsanmoin05 said. Its your best bet

Actually you could make it so anytime you add something to the dictionary you add 1 to a value and anytime somethings removed remove 1. Then just use this number

1 Like

That’s something I didn’t think of

its simple things like these we all totally dont think of, I wouldnt blame you, I had to go touch grass to figure it out

1 Like

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