lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

2013/2/6 TNHarris <>:
> From the manual:
>      function concat_event (op1, op2)
>        if (type(op1) == "string" or type(op1) == "number") and
>           (type(op2) == "string" or type(op2) == "number") then
>          return op1 .. op2  -- primitive string concatenation
>        else
>          -- call the metamethod
>        end
>      end
>      function len_event (op)
>        if type(op) == "string" then
>          return strlen(op)      -- primitive string length
>        else
>          -- call the metamethod
>        end
>      end
> So if I wanted to, say, return the character length of a UTF-8 string, I
> couldn't use
>      getmetatable("").__len = utf8length
> What is the motivation for not allowing the __concat and __len metamethods to
> be set on strings?

You are allowed to set them, although at present there is not much point
in setting __len for strings. Setting __concat is highly useful, though:
it allows you to concatenate strings with other things than numbers.
Specifically, the universal concatenator

    universal = function(a,b) return tostring(a)..tostring(b) end
    getmetatable("").__len = universal

allows you to concatenate a string with anything, respecting the
individual __tostring metamethods.

You must bear in mind that most metamethods not override anything. As
Roberto has put it, they are called when Lua does not know what to do.
They are fallbacks in cases where Lua would just return nil, or give
an error, or resort to something desperate like the default length
function for tables, which is undefined except in a common but very
special case. To get them to work for you full-time, you must go to
considerable lengths to make sure that Lua always does not know what
to do. Like proxy tables, for example.