Fix tonumber() to match standard Lua's behavior more closely.

This commit is contained in:
Ian Farmer
2008-10-10 23:37:47 +00:00
parent 79e25ac436
commit bf90c74582
3 changed files with 21 additions and 2 deletions

View File

@@ -366,8 +366,16 @@ public class LString extends LValue {
public LValue luaToNumber( int base ) {
if ( base >= 2 && base <= 36 ) {
String str = toJavaString().trim();
if ( ( base == 10 || base == 16 ) && ( str.startsWith("0x") || str.startsWith("0X") ) ) {
base = 16;
str = str.substring(2);
}
try {
return LInteger.valueOf( Integer.parseInt( str, base ) );
long x = Long.parseLong(str, base);
if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE)
return new LDouble((double) x);
else
return LInteger.valueOf((int) x);
} catch ( NumberFormatException nfe ) {
if ( base == 10 ) {
try {

View File

@@ -207,6 +207,17 @@ print( 'pcall(tonumber,{"one","two",a="aa",b="bb"})', pcall(tonumber,{"one","two
print( 'pcall(tonumber,"123.456")', pcall(tonumber,"123.456") )
print( 'pcall(tonumber," 123.456")', pcall(tonumber," 123.456") )
print( 'pcall(tonumber," 234qwer")', pcall(tonumber," 234qwer") )
print( 'pcall(tonumber,"0x20")', pcall(tonumber,"0x20") )
print( 'pcall(tonumber," 0x20")', pcall(tonumber," 0x20") )
print( 'pcall(tonumber,"0x20 ")', pcall(tonumber,"0x20 ") )
print( 'pcall(tonumber," 0x20 ")', pcall(tonumber," 0x20 ") )
print( 'pcall(tonumber,"0X20")', pcall(tonumber,"0X20") )
print( 'pcall(tonumber," 0X20")', pcall(tonumber," 0X20") )
print( 'pcall(tonumber,"0X20 ")', pcall(tonumber,"0X20 ") )
print( 'pcall(tonumber," 0X20 ")', pcall(tonumber," 0X20 ") )
print( 'pcall(tonumber,"0x20",10)', pcall(tonumber,"0x20",10) )
print( 'pcall(tonumber,"0x20",16)', pcall(tonumber,"0x20",16) )
print( 'pcall(tonumber,"0x20",8)', pcall(tonumber,"0x20",8) )
-- tostring
print( 'pcall(tostring)', pcall(tostring) )

View File

@@ -1 +1 @@
version: 0.53
version: 0.54