lua-users home
lua-l archive

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


Yes - let me add a 'ping' for that too!

I'm just completing a bitfield library which would benefit from this. I have
a 'tostring' which works either as a method or as a metamethod, but the
corresponding 'tonumber' only works as a method:

s = bf:tostring() -- good
s = tostring(bf) -- good
n = bf:tonumber() -- good
n = tonumber(bf) -- bad

It would also be useful if the manual had a complete list of metamethods
somewhere for reference. Either list all 'the other' metamethods at the end
of the metatables section with links to the library function that uses them,
or just make sure they are all in the index (conveniently the double
underscore prefix will make sure they all get sorted together).

> Date: Fri, 26 Jul 2013 10:17:26 -0500
> From: Andrew Starks <andrew.starks@trms.com>
> Subject: A ping for __tonumber
> 
> I've gone over the archives and read past posts on the __tonumber
> metamethod idea. In light of work on 5.3, I wanted to throw out that
> __tonumber would be welcomed.
> 
> Within my own Lua code, I often want to turn an object into a plain
> number. The meta-methods can effectively do most of what I want, but
> not when I'm dealing with relational operators when one side of is an
> actual number.
> 
> `tonumber` might be more appropriate than going through the work of
> defining every arithmetic metamethod that I may or may not need for
> that object (it's tedious).
> 
> Finally, __tonumber just feels... missing. I even had to triple check
> that it wasn't in 5.2, lest I embarrass myself. :)
> 
> Of course, I'm happy to monkeypatch tonumber (and may apply the power
> patch that I found in my research). My opinion is that it would be
> generally helpful, especially when/if coercion of strings to numbers
> should go away[1].
> 
> -Andrew
> 
> [1]I'm in the habit of calling tonumber whenever I need a number, in
> case I get a string. I use it as a silent protest that Lua coerces
> strings without me asking.