简单介绍lua值的八种基本类型: number, string, boolean, table, function, nil, userdata,thread.
请查阅 TutorialExamples 获取示例. 我们使用函数 print()
输出值 或 运算结果. 围绕参数的括号很重要, 如果省略, 则会导致错误.
-
> print(2) -- print the number two. 2 > print("hello") -- print the string hello. hello
Numbers
Number 类型代表的是浮点数(小数). 并无单独的整数类型(非小数).
Lua 允许数值进行简单的加, 减, 乘, 除运算.
-
> print(2+2) 4 > print(2-7) -5 > print(7*8) 56 > print(7/8) 0.875
注意: 这些数字不会四舍五入变为整数. 他们都是浮点数. 我们可以通过 =
声明一个变量值.
-
> x = 7 > print(x) 7
=
操作符, 声明变量
x
的值为数值 7. 函数
print()
可输出
x
的值. 接下来, 我们就可以使用变量
x
, 进行其他运算.
-
> x = x * 9 > print(x) 63 > print(x*2) -- will not change the value of x 126 > print(x) 63
更多 Lua's number 类型信息, 请查阅 NumbersTutorial.
Numbers Tutorial |
Internal representation
很多编程语言, 支持下列的一种或多种数据类型:
- Integer (整形)
- Unlimited precision integer (无精度限制的整数)
- Single precision floating point (单精度浮点数)
- Double precision floating point (双精度浮点数)
- Complex fun (复合数)
Lua 内部只支持一种数据类型, 及浮点数. 默认是双精度浮点数, 但是也可以重新编译Lua, 让其支持单精度浮点数.如果你并不熟悉浮点数, 建议阅读 FloatingPoint .
请记住, 如果你使用带小数部分的数值, 一旦将其存储于一个受限的空间内, 就会引发错误.短的 或 无重复形式的数值, 容易转换为二进制, 因此, 不要以为所有的小数值都是安全的.还有就是, 请勿将操作符 ==
与小数一起使用, 四舍五入在一段时间内, 不能处理较大的数字.
如果你使用的是一个整数 (无小数部分), 大小未达到 2^53, 那么一切都不是问题.
Using numbers
我们可以使用 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
-
> = 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
The math library
Lua 自带math库 (见参考手册第 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
Conversion
调用函数 tonumber()
, 可将字符串转换为数值.
-
> = tonumber("123") + 25 148 > x = tonumber("123.456e5") > print(x) 12345600
Coercion
Lua 进行计算时, 会自动转换字符串 和 数值类型. 例如, 如果你尝试对一个字符串进行算术运算, Lua 会先将string转换为string, 否则运算无效. 如果字符串不能转化为数字, 就会产生错误.这种自动类型的转换称为 coercion.
-
> = 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
例外: 比较操作符 (== ~= < > <= >=
) 不能 转变它们的参数.(不)等于操作符, 处理数值时, 不同于字符串(任何非数值型).有序比较操作符, 一旦感知到它们是不同的类型, 便会抛出一个错误.
-
> = 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]: ?