lua-users home
lua-l archive

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

于 2012-6-13 19:21, Dirk Laurie 写道:
It seems to be impossible to override arithmetic operators on
strings.  One can for example set the __add metamethod, but
it only gets called when at least one of the strings cannot be
coerced to a number.  For example:

    getmetatable''.__add = function(x,y) return x..y end
    'a'+'b' -->  'ab', fine
    '1'+'2' -->  3

No, you can't do such in Lua.

Lua would automatically call tonumber on strings when doing arithmetic operation.
and the same applied to concat operation on numbers.


"3" + "4"      =>  7
3  .. 4        =>  "34"  (note the space between number and ..)