Why is #table printing 0

module.Abilities = {E = module.BarrierWall, Q = module.BarrierRemove}
1 Like

Tables in Lua(u) are comprised of two sub data structures: the array and the hash-map (dictionary). The length operator only reports the number of values in the array component; the table you’ve presented us is a dictionary. To get a table’s full length, you must implement a your own counting function:

local function length(container: {}): number
    local sum = 0

    for _ in container do
        sum += 1
    end

    return sum
end

If you intend to use this for selecting a random ability, know that it will not work. Using a random number between 1 and the table length only works for arrays as it takes advantage of each value’s ascending numerical index. You will need to collect an array of your dictionary’s keys, select one at random using that method, then index the dictionary

1 Like

Dictionary pairs don’t count towards the length. # gets the length of the array component of a table.

local data = {"A", "B", "C"}
print(#data) --> 3

local data = {A = 1, B = 2}
print(#data) --> 0

local data = {"A", B = 2, "C", D = 4}
print(#data) --> 2
1 Like

the # operator only counts numerical keys.

look at @bluebxrrybot’s example

You can get the exact number of data by doing this:

local count = 0
for _ in pairs(your_table) do
    count+=1
end
print(count)