Lua -<2>- 类型和值

2018-06-05  本文已影响14人  _小圆球_
print(type("Hello world")) --> string 
print(type(10.4*3)) --> number 
print(type(print)) --> function 
print(type(type)) --> function 
print(type(true)) --> boolean 
print(type(nil)) --> nil 
print(type(type(X))) --> string 

变量没有预定义的类型,每一个变量都可能包含任一种类型的值。

print(type(a)) --> nil ('a' is not initialized) 
a = 10 
print(type(a)) --> number 
a = "a string!!"
print(type(a)) --> string 
a = print -- yes, this is valid! 
a(type(a)) --> function 

注意上面最后两行,我们可以使用 function 像使用其他值一样使用。一般情况下同一变量代表不同类型的值会造成混乱,最好不要用,但是特殊情况下可以带来便利,比如 nil。

4   0.4    4.57e-3    0.3e12    5e+20 
a = "one string"
b = string.gsub(a, "one", "another") -- change string parts 
print(a) --> one string 
print(b) --> another string 

string 和其他对象一样,Lua 自动进行内存分配和释放,一个 string 可以只包含一个字母也可以包含一本书,Lua 可以高效的处理长字符串,1M 的 string 在 Lua 中是很常见的。可以使用单引号或者双引号表示字符串

a = "a line"
b = 'another line'

为了风格统一,最好使用一种,除非两种引号嵌套情况。对于字符串中含有引号的情况还可以使用转义符\来表示。Lua 中的转义序列有:

\a bell 
\b back space -- 后退
\f form feed -- 换页
\n newline -- 换行
\r carriage return -- 回车
\t horizontal tab -- 制表
\v vertical tab 
\\ backslash -- "\" 
\" double quote -- 双引号
\' single quote -- 单引号
\[ left square bracket -- 左中括号
\] right square bracket -- 右中括号

还可以使用[[...]]表示字符串。这种形式的字符串可以包含多行也,可以嵌套且不会解释转义序列,如果第一个字符是换行符会被自动忽略掉。这种形式的字符串用来包含一段代码是非常方便的。

运行时,Lua 会自动在 string 和 numbers 之间自动进行类型转换,当一个字符串使用算术操作符时,string 就会被转成数字。

print("10" + 1) --> 11 
print("10 + 1") --> 10 + 1 
print("-5.3e - 10" * "2") --> -1.06e-09 
print("hello" + 1) -- ERROR (cannot convert "hello") 

反过来,当 Lua 期望一个 string 而碰到数字时,会将数字转成 string。

print(10 .. 20) --> 1020 

..在Lua中是字符串连接符,当在一个数字后面写 ..时,必须加上空格防止被解释错。

尽管字符串和数字可以自动转换,但两者是不同的,像 10 == "10"这样的比较永远都是错的。如果需要显式将 string 转成数字可以使用函数 tonumber(),如果 string 不是正确的数字该函数将返回 nil。

line = io.read() -- read a line 
n = tonumber(line) -- try to convert it to a number 
if n == nil then
 error(line .. " is not a valid number") 
else 
 print(n*2) 
end 

反之,可以调用 tostring()将数字转成字符串,这种转换一直有效:

print(tostring(10) == "10") --> true 
print(10 .. "" == "10") --> true 
上一篇 下一篇

猜你喜欢

热点阅读