Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why they can't recognize lengh of my dictionary?

Asked by 3 years ago
1local Foods = {
2    Salt = {Taste = "Salty", Hunger = "1"},
3    Cookie = {Taste = "Sweet", Hunger = "100"}
4}
5 
6print(#Foods) --- Output =  0

I dont know why this happen. Why they cant recognize the length?

1 answer

Log in to vote
1
Answered by 3 years ago

Dictionaries don't really exist in Lua. There's only tables.

Anyway, there are no values in your tables. You only assigned values within your table. If you do want to check how many keys and all are in your table, you must use a for loop and count how many entries there are.

01local Foods = {
02  Salt = 1,
03  Cookie = 2
04}
05 
06print(#Foods) --- Output =  0
07 
08local entriesNumber = 0
09for i, _ in pairs(Foods) do
10  entriesNumber = entriesNumber + 1
11end
12 
13print(entriesNumber) -- Output = 2
0
Btw, the i variable is not needed either. You can just replace it with an underscore, if you care so much about that. satyajit_ray 60 — 3y
Ad

Answer this question