Module Script does not recognize entries

Good morning! ,

I am currently working on a module script that will pick a random entry and output stored values:

local HOLDERTABLE = 
 {
["TEST"] = {
	["subHolder_1"] = "HOLDER",
	["subHolder_2"] = "HOLDER"
	},
	
["TEST_2"] = {
		["subHolder_1"] = "HOLDER",
		["subHolder_2"] = "HOLDER"
	},
}


return HOLDERTABLE

However, when I use
print(#HOLDERTABLE), the returned value is 0. I was wondering why the HOLDERTABLE does not consider the two holder values as members of the HOLDERTABLE, and what could be done to work around this issue.

Thank you.

The length operator only works for arrays, not dictionaries. If you want to see the length of a dictionary you have to do something like this:

local function GetLengthOfDictionary(t)
    local keys = {}

    for key in t do
       -- insert the index into the keys table
       table.insert(keys, key)
    end

    return #keys -- return the length of the keys array
end
1 Like

You can’t get the length of a dictionary. But if you really want to, you can use metatables to give the dictionary that ability:

local data = {
    Coins = 1000,
    Gems = 20,
    Rebirths = 0,
}

print(#data) --> 0

setmetatable(data, {
    __len = function(self)
        local count = 0
        for _, _ in pairs(self) do
            count = count + 1
        end
        return count
    end
})

print(#data) --> 3

You can also just make a function to get the length:

local function getlength(data)
    local count = 0
    for _, _ in pairs(data) do
        count = count + 1
    end
    return count
end
2 Likes

The metatable function works like a charm, thank you.

The length operator only working on arrays was a huge oversight on my part

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