Number类型在LUA语言中的演化1

来源:互联网 发布:python运行环境搭建 编辑:程序博客网 时间:2024/06/06 13:12

 


Numbers in Lua

●  Since its first version (1993), Lua has had one 
      single kind of number
●  First versions used float
●  Changed to double in version 3.1 (1998)
●  mainly because programmers needed 32-bit values
●  a float has only 24 bits of mantissa, a double has 53  bits. 

在LUA在1993年时,Number通过float来实现。在98年时,被改成double数据类型。


使用Double数据类型的优点:
●  Well-defined rules (IEEE), including error and 
   overflow handling (±inf, NaN)
●  Hardware support in conventional platforms
    ● even in 1998
●  53 bits is enough for most counting purposes
    ●  1 petabyte
    ●  1 million times the world population
    ● 300  000 years in seconds
    ●  20% of total global wealth in cents of dollars
1、被IEEE标准定义,包括错误
2、在98年时候被常见硬件平台支持
3、53bit足够被大,够使用
缺点:
●  Big and slow for restricted hardware
●  Awkward for bitwise operators
    ●  should they operate on 53 bits?
    ●  ~0 is 0xFFFFFFFF or -1?
●  Some algorithms need 64 bits
    ●  cryptography, encodings
●  Some data need 64 bits
    ●  handles
●  Integers already present in Lua as second  class values.
    ● several library functions use integers (e.g., indices 
       in the string library)
    ●  conversions not well specified and/or not efficient
    ●  string.sub(s, -3.4, 8.7)
●  Confusing in the C API
    ●  conversions always lose bits in some direction

1、在受限制的硬件上太大,太慢
2、使用按位操作符太麻烦
3、一些算法需要64位支持,Double 53位不足够大
4、一些大数据需要64位支持
5、整数已经在lua中存在
6、C API容易产生混乱


tonumber (e [, base])
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral.
The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.
In base 10 (the default), the number can have a decimal part, as well as an optional exponent part . In other bases, only unsigned integers are accepted.


尝试把参数e转换成number类型。如果参数已经是number类型或者string类型,通过tonumber()把e参数转换成Number类型数据。
[base]可选参数,可以指定基数。基数范围可以从2到36.
当base=10时, 大写字母A 或者小写字母a表示10.默认情况下,base=10.
只有在基数为10的情况下,才能有符号和小数部分。其他情况下,只能为无符号整数才能做为参数。

print(tonumber(-1,2))           --error  print 4294967295
print(tonumber(-1,10))          --print -1
print(tonumber(00011110000,2))  --print 240
print(tonumber("0x0a",16))      --print 10
print(tonumber("0x0a",10))      --print 10
print(tonumber("a",16))      --print 10
print(tonumber("a",10))      --print nil
print(tonumber(0x0a,16))        --print 16
print("0x0a")                   --print 0x0a
print(0x0a)                     --print 10

 

 

          

 

   

                               

0 0