Usage of __len to get length of k,v dictionary

Howdy,

I’m working on an inventory system and I need to get the size of a player’s inventory so I can effectively display it using a scrollingframe.

I did some reading on this devforum & developer wiki and found that __len is the only metamethod that I can use to get the length of a k,v dictionary (the # operator doesn’t work in this case, because my keys are non-numeric).

Can someone help me understand how to correctly use the __len metamethod to get the length of a k,v dictionary?

Note: I know that I can use this code –

local length;
for k,v in pairs(DICTIONARY) do
    length = length + 1
end

– but I don’t want to constantly loop through a player’s inventory whenever it gets updated.

In 5.1 (the version of Lua that Roblox uses), the __len metamethod doesn’t respect tables currently. It only works on userdatas for some reason. Overloading the # operator on a userdata just to get the length of something completely different doesn’t seem feasible/desirable here, so just make a wrapper function.

local function len(t)
    local n = 0

    for _ in pairs(t) do
        n = n + 1
    end
    return n
end
12 Likes