数字教程 |
|
某些语言默认支持以下一个或多个数字类型
5.3 版本增加了整数支持(数字可以是整数),但大部分以下信息仍然有效,因为它们会在需要时被转换。
为了简洁起见,Lua 只支持一种数字类型:浮点数。默认情况下,这些是双精度浮点数。但是,如果您愿意,Lua 可以很容易地重新编译以支持单精度浮点数。如果您不熟悉浮点数,最好阅读有关 浮点数 的信息。
要记住的主要一点是,如果您使用带有小数部分(或进行除法)的数字,它们可能会有舍入误差。
同样,在十进制中无限循环的数字在二进制中不会无限循环,所以不要假设任何小数“安全”。要记住的主要一点是,不要使用 == 运算符处理小数,因为它检查的是完全相等。另一件事是要注意,您的代码编写方式应避免舍入误差随时间累积到很大的量。
如果您的数字是整数(没有小数部分),并且它们不达到 2^63;那么您就不需要担心这些问题。
我们可以使用 Lua 交互式命令行提示符作为计算器,方法是在表达式前加上 =,例如:
Lua 5.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio > = 1 1 > = 1 + 2 3 > = 3.1415927 3.1415927 > = 5 / 6 0.83333333333333
<value>e<exponent> 或 <value>E<exponent> 的形式表示数字,这代表 <value> * 10 ^ <exponent>。> = 1.2345e6 1234500 > = 543.21E8 54321000000 > = 2.56e-4 0.000256
> width = 7.5
> height = 12.7
> = width * height
95.25
> depth = 2.8
> area = width * height
> volume = area * depth
> print(area, volume)
95.25 266.7
Lua 配备了一个数学库(请参阅参考手册的 5.6 节 [1])。提供的函数如下:
math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.floor math.fmod math.frexp math.ldexp math.log math.log10 math.max math.min math.modf math.pow math.rad math.random math.randomseed math.sin math.sinh math.sqrt math.tan math.tanh
> = math.sqrt(101) 10.049875621121 > = math.pi 3.1415926535898 > = math.sin( math.pi/3 ) 0.86602540378444
您可以使用 tonumber() 函数将字符串转换为数字。它接受一个字符串参数并返回一个数字。
> = tonumber("123") + 25 148 > x = tonumber("123.456e5") > print(x) 12345600
对于将整数转换为浮点数,此计算将返回已转换整数的十进制格式
> = (16 ^ 13) + 10 - (16 ^ 13) 10.0
Lua 会自动将字符串和数字类型转换为正确的格式以执行计算。例如:如果您尝试对字符串应用算术运算,Lua 将首先尝试将该字符串转换为数字。否则,该操作将无法正常工作。如果字符串无法转换为数字,则会引发错误。这种自动类型转换称为强制类型转换。
> = 100 + "7" 107 > = "1000" + 234 1234 > = "hello" + 234 stdin:1: attempt to perform arithmetic on a string value stack traceback: stdin:1: in main chunk [C]: ? > = 234 + "1000" 1234
"hello" 无法转换为数字,因此会发生错误。在静态类型语言(例如 C)中,这会引发错误,因为您无法在不进行类型转换的情况下将值赋给类型不兼容的变量。这在 Lua 中可行,因为它动态类型。一个显著的例外:比较运算符(== ~= < > <= >=)*不*会强制转换其参数。(不)相等运算符认为数字与其字符串表示(或任何非数字类型)*不相等*。当您向有序比较运算符提供不同类型的参数时,它们会引发错误。
> = 100 == "100" false > = 100 ~= "hello" true > = 100 ~= {} true > = 100 == tonumber("100") true > = 100 <= "100" stdin:1: attempt to compare number with string stack traceback: stdin:1: in main chunk [C]: ?