
Lua的基础语法超粗备忘录,可以为自己随时添加。
Lua特点
- 变量没有类型的动态类型语言
- 所有值都可以存储在变量中
- 所有值都可以是函数参数和返回值
- 未初始化变量的值为nil
- 条件判断为nil或false时为false
Lua类型
Lua有以下几种类型:
- 零
- 布尔值:布尔值
- 数量:数量
- 字符串:字符串
- 函数:函数
- 表:表
- 线程:线程
- 用户数据:用户数据
其中,函数、表、线程和用户数据称为对象,它们的引用存储在变量中。
变量和范围
变量声明如下:
-- global variable
foo = "Foo"
-- local variable
local bar = "Bar"
全局变量存储在一个称为Lua环境表的特殊位置,可以从任何地方引用,也可以通过在控制结构或函数内部声明局部变量来缩小范围。
function add(a, b)
-- Valid only within functions
local temp = a
return temp + b
end
另外,如果通过用 do 和 end 括起来显式定义“块”,则内部将成为局部变量的范围。
do
-- Valid only within this block
local temp = 1
end
从处理速度和内存的角度来看,应尽可能使用局部变量。
表
该表定义如下。
t = {}
像数组一样使用
表可以像数组一样使用。
t = {}
-- use like an array
-- index from 1
t[1] = "aa"
t[2] = 123
也可以统写为:
t = {
"aa",
123
}
像关联数组一样使用它
表也可以像关联数组一样使用。
t = {}
t["key1"] = 123
t["key2"] = "test"
写成如下就可以了:
t = {
key1 = 123,
key2 = "test"
}
像class一样使用
由于表的元素可以存储任何类型,因此可以像类一样使用,如下所示。
vec3 = {
x = 0,
y = 0,
z = 0,
Length = function(self)
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
end
}
vec3["x"] = 1
vec3["y"] = 2
vec3["z"] = 3
length = vec3:Length()
还可以像这样定义构造函数:
vec3 = {}
vec3.new = function(x, y, z)
local obj = {
x = x,
y = y,
z = z,
Length = function(self)
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
end
}
return obj
end
vec3_1 = vec3.new(1,2,3)
length_1 = vec3_1:Length()
控制语法
if语句
foo = 123
if foo >= 100 then
print("A")
else
print("B")
end
while语句
i = 0
while i < 10 do
print (i)
i = i + 1
end
对于声明
-- start value, end value, increment
for i = 0, 9, 1 do
print(i)
end
重复声明
i = 0
repeat
print (i)
i = i + 1
until (i >= 10)
功能
函数的处理如下:
-- Function definition
function add(a, b)
return a + b
end
-- call
result = add(1, 3)
也可以返回多个返回值。
function func()
return 123, "abc"
end
a, b = func()
print(a)
print(b)
上面说过,在Lua中所有的值都可以存储在变量中,函数也可以存储如下。
function func()
return 123
end
-- Store function in variable
fooFunc = func
print(fooFunc())
协程
协程是这样使用的:
-- create coroutine
local testRoutine = coroutine.create(
function(initVal)
coroutine.yield(initVal)
coroutine.yield(1)
end
)
-- Execute the coroutine, processing proceeds until it is yielded
local status1, value1 = coroutine.resume(testRoutine, 123) -- You can pass the initial value as the second argument
print(value1) -- 123
print(coroutine.status(testRoutine)) -- suspended
-- run coroutine until next yield
local status2, value2 = coroutine.resume(testRoutine)
print(value2) -- 1
print(coroutine.status(testRoutine)) -- suspended
-- status becomes dead when the coroutine finishes
local status3, value3 = coroutine.resume(testRoutine)
print(value3) -- nil
print(coroutine.status(testRoutine)) -- dead
还有一种使用coroutine.wrap的方法如下:
function func()
coroutine.yield "1"
coroutine.yield "2"
return "end"
end
-- Create coroutines from functions
local co = coroutine.wrap(func)
-- call
print(co())
print(co())
print(co())
评论
-- one line comment
--[[
multi-line comment
multi-line comment
]]
错误
使用错误函数引发错误。
error("error")
…
以上是关于Lua基础语法的全部内容,如果你有任何反馈,请随时在本页面下方留言。