lua 是动态类型语言,变量使用前不需要定义类型,在使用时直接赋值即可。
值可以存储在变量中,作为参数传递或作为结果返回。
lua中有八个基本数据类型:
通过函数 type 可以返回一个值或一个变量所属的数据类型。
- print(type("hello"))
- print(type(23))
- print(type(23.3))
- print(type(true))
- print(type(nil))
- print(type(function() end))
输出如下
string
number
number
boolean
nil
function
整数和浮点数在lua中,都属于 number 实数类型。
nil 是一种空数据类型,在 lua 中将 nil 用于表示“无效值”。变量在首次赋值前的默认值,就是 nil,将 nil 赋给全局变量后,即等同于删除该变量。
- -- 定义变量,但是没有赋值
- local abc
- print(abc)
- print(type(abc))
-
- -- 为变量赋值
- abc = "hello"
- print(abc)
- print(type(abc))
输出如下:
nil
nil
hello
string
在赋值前该变量及变量类型都为nil,赋值后变量及变量类型随之改变。
布尔类型,取值只有 true 和 false。
lua 中,当变量为 nil 或 false 时,其布尔值为 false,其他数值均为 true。
- -- 变量未赋值时,值为nil
- local boo
- if boo then
- print("true")
- else
- print("false")
- end
-
- -- 给变量赋值为 false
- local boo = false
- if boo then
- print("true")
- else
- print("false")
- end
输出都为 false
false
false
- -- 给变量赋值为0
- local boo = 0
- if boo then
- print("true")
- else
- print("false")
- end
- -- 给变量赋值为空字符串
- local boo = ""
- if boo then
- print("true")
- else
- print("false")
- end
当变量值为非nil 及 false 时,取值都为 true。
true
true
lua 中没有区分整数和小数,所有数字统一为number类型,即实数。
number的计算方法主要来自于 math 类
- -- 向上取整
- print(math.ceil("3.1415926"))
- -- 向下取整
- print(math.floor("3.1415926"))
- -- 绝对值
- print(math.abs(-3.1415926))
输出如下
4
3
3.1415926
在 lua 中字符串表示有三种方式:
- local s1 = "hello\nworld"
- local s2 = 'hello\nworld'
- local s3 = [[hello\nworld]]
-
- print(s1)
- print(s2)
- print(s3)
其中在单引号、双引号定义的字符串,如果存在转义符时,会对其转义输出;
而由 [[]] 包裹的字符串,不会对转义字符进行转义,仅将其原样输出。
hello
world
hello
world
hello\nworld
字符串的内化:如果有多个完全一样的字符串,在lua中仅会保存一份。
- local ta = {
- name = "ticktok",
- age = 23,
- sex = true,
- honor = {
- "swim",
- "run",
- "sleep"
- },
- 001002003, -- 索引没有,相当于[1]
- 7759521, -- 索引没有,相当于[2]
- [1] = "hello", -- 索引重复,该值不会被保存
- ["key"] = "value",
- [1.2] = "world",
- }
定义一个 table 类型的数据,前边是索引,后边是索引对应的数据。
需要注意的是:
即
- local ta = {
- 001002003, -- 索引没有,相当于[1]
- 7759521, -- 索引没有,相当于[2]
- }
- print(ta[1])
输出如下
1002003
- local ta = {
- [1.2] = "world",
- [1.2] = "world23",
- }
- print(ta[1.2])
输出如下
world23
- local ta = {
- [1] = "hello", -- 索引重复,该值不会被保存
- 001002003, -- 索引没有,相当于[1]
- 7759521, -- 索引没有,相当于[2]
- }
- print(ta[1])
输出如下
1002003
- local ta = {
- honor = {
- "swim",
- "run",
- "sleep"
- },
- }
- print(ta.honor[1])
输出如下,数据的索引从1开始
swim
print(ta["abc"])
输出
nil
lua 中函数也可以作为变量使用。
- -- 定义一个函数
- local function foo()
- local x = 3
- local y = 7
- return x + y
- end
- -- 将函数赋值给变量
- local c = foo
- print(c())
- -- 将函数赋值给变量2
- local c = foo()
- print(c)
将函数赋值给变量时,函数名后不带()和带有()在引用变量时会有区别:
函数也可以如下使用,将赋值和定义放在一起。
- local c2 = function()
- local x = 3
- local y = 7
- return x * y
- end
- print(c2())
在 lua 里,最主要的线程是协同程序(corourtine),与线程(thread)类似,拥有独立的栈、局部变量和指令指针,可以跟其他协同程序共享全局变量等信息。
线程与协程的区别:
一种由用户自定义的数据,用于表示一种由应用程序或 C/C++ 语言库所创建的类型,可以将任意C/C++ 的任意数据类型的数据存储到 lua 变量中调用。
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=11o1a9mh55g54