I have a table, lets call Table. I have ~16 other tables in it. When i do
for i,v in pairs(Table) do
print(v)
end
it’ll print ~16 items.
When i do #Table, it says 0. I have no idea whats wrong. Heres a pic
Here is the output of when i print the contents and at the bottom you can see it says 0 which is the print(#Table)
The reason this is happening is, keys would not count when using the # operator. For that reason I assume you have these 16 tables set in a dictionarry. Can you send the code or the table’s layout please? Here is a post that explains things really well
So I understand now that someone told me it only works for integer indices. So i’ll tell you what i’m tryna do. The table is set via a lot of random stuff so I cant exactly show it so i’ll give an examplek
What I want is to select a random table from within the dictionary thing. So I am doing Table[math.random(1,#Table)] and it is saying that there its empty.
First of all, keys are not presented as integers as you said, so even if you knew how many tables there are, Table[math.random(1,#Table)] isn’t valid, beacuse it’s looking for a random integer, and here we have keys.
I guess here is what you can do!
Use this function to know how many keys there are
function len(tab)
local sum = 0
for _, v in pairs(tab) do
sum = sum + 1
end
return sum
end
And since all the tables are named "ItemN" where N is the number of the table, you can do this
The length operator does not account for string indices in tables. If you wanted to, you can use metatables:
local mt = {
__len = function(tbl)
local count = 0
for index, value in pairs(tbl) do
count = count + 1
end
return count
end
}
local Table = {
["Item1"] = {1};
["Item2"] = {2};
["Item3"] = {3};
}
setmetatable(Table, mt)
print(#Table)