lua-users home
lua-l archive

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

  The behaviour of tonumber(e[,base]) does not quite match the
documentation when a base other than 10 is specified.  Two documentation
issues and a third bug issue...

  First, range of base:  The documentation claims that "The base may be any
integer between 2 and 36 inclusive" (6.1) yet the routine will accept 0-36
without error.  Since strtol() accepts 0 as an "auto-detect base"
specifier, maybe the inclusion of 0 is intentional, if so docs should
probably mention this, but in any case 1 as a base should be disallowed.

  Second, return value docs:  The documentation claims that "If the
argument is already a number or a string convertible to a number, then
tonumber returns that number; otherwise, it returns nil."  (6.1)  However,
that's only strictly true if a base is not specified.  If you pass in a
value for a base with potentially bad data (e contains digits >= base) then
you won't get the original number back.  Example:

  > nil

  Of course this represents bad data as 9 cannot be a base 8 number, so nil
may be an appropriate return value since if 9 were converted to a string it
would not be "a string convertible to a number" given the specified base. 
But the documentation seems unclear on this, and may imply that you would
receive 9 (base 10) as the return value since 9 "is already a number".
  The documentation could probably be fixed by adding something like "...
or a string convertible to a number _in the default or specified base_ ..."
or in some other way clarifying that a string conversion is always implied
when a base is specified.

  Third, erroneous zero returns:  tonumber() should handle the
zero-as-error return of strtol().  The empty string is the only example
that I'm aware of, which could be checked for in advance or check the
endptr return value against the original string pointer for equality. 

  > 0

  should have returned nil according to all documentation since "" is
neither a number or convertible string.