__len metamethod not being invoked?

I want to get the “length” of a dictionary via the unary length operator #. I made myself this:

local t = {
    a = 'b',
    one = 2,
    yes = "no",
    True = false
};

setmetatable(t, {__len = function(t)
    local len = 0;
    
    for k, v in pairs(t) do
        len = len + 1;
    end
    return len;
end};

print(#t);

Output:

0

Expected output:

4

1 Like

The __len metamethod is available to only Lua 5.2+. Roblox uses Lua 5.1.4.

5 Likes

I believe it is usable on userdatas in lua 5.1 though.

local new = newproxy(true)
getmetatable(new).__len = function()
    return 4
end
print(#new)
5 Likes

It is explained in the wiki page here

__len(table) Fired when the * length operator is used on the Object. NOTE: Only userdatas actually respect the __len() metamethod in Lua 5.1