Lua 基础知识
基础
- 字符串连接,操作符 ..(两个点)
- 函数 type()能够返回一个值或一个变量所属的类型
- assert()判断
- --开头表示单行注释
- 多行注释
# 格式一
--[[
多
行注释
]]
# 格式二
--[==[
[[多行注释]]
]==]
基础数据类型
$ cat << EOF > test.lua
print(type(nil))
print(type(true))
print(type("helloworld"))
print(type(18))
print(type(18.8))
print(type(table))
print(type(print))
EOF
$ lua test.lua
nil
boolean
string
number
number
table
function
table
表(table) 是 Lua 唯一的数据类型,可以理解为 Python 中的数组、字典等
- 使用 {}定义,{}表示空表
- 使用 key=value时,key不需要单引号或双引号,若 key 是特殊字符,可以使用[key]=value形式
- 使用 []操作表里的元素
- 若 key是字符串,可使用.操作
- #可以计算 table 的长度
- 使用 ipairs()/pairs()函数遍历表
- table 也可以作为函数的参数
- 示例
local a = {1, 2, 3}
local b = {one=1, 2, [3]=3, ['a']={}}
print(a[1])  -- 1
b['two'] = 2
print(b['one'])
print(b.one)
a.xfunc = function(a)
    print(a)
end
-- 遍历 table
for i=1, #b do
    print(b[i], ', ')
end
for i,v in ipairs(b) do
    print(b[i], ', ')
end
for k,v in ipairs(b) do
    print(k, ' = ', v)
end
变量
- 局部变量:使用 local声明的变量,作用域当前代码块,推荐变量的声明方式
- 全局变量:没有使用 local声明的变量
local x = 1
local x, y = 1, 'ok'
local x, y = 1  -- 等价于 x = 1, y = nil
local x = nil   -- 删除变量
-- 语句块
do
    local y = 2
end
说明:
- 若变量没有赋值,默认值为 nil
- _表示占位符,同 Python 的使用,用来忽略变量
- 常量通常用大写字母表示,使用 local声明,如:local PI = 3.1415
算术运算符
- +加法
- -减法
- *乘法
- /除法
- ^指数
- %取模
说明:
关系运算符
- <小于
- >大于
- <=小于等于
- >=大于等于
- ==等于,若类型不同,返回- false。可使用- tonumber()/tostring()转化数字或字符串
- ~=不等于,若类型不同,返回- false
逻辑运算符
- and逻辑与,- x and y若 x 是真,返回 y,否则返回 x
- or逻辑或,- x or y若 x 是真,返回 x,否则返回 y
- not逻辑非
流程控制
条件 if-else
该部分语法和 shell 的 if 很相似
-- 基本结构
if conditions then
    ....
end
if conditions then
    ....
else
    ...
end
if conditions then
    ....
elseif conditions then
    ....
else
    ...
end
-- 单个 if 分支型
x = 10
if x > 0 then
    print("x is a positive number")
-- 两个分支 if-else 型
x = 10
if x > 0 then
    print("x is a positive number")
else
    print("x is a non-positive number")
end
-- 多个分支 if-elseif-else 型
score = 90
if score == 100 then
    print("Very good!")
elseif score >= 60 then
    print("Passed!")
    --此处可以添加多个elseif
else
    print("Sorry!")
end
while
# 定义
while 表达式 do
--body
end
# 示例
x = 1
sum = 0
while x <= 5 do
    sum = sum + x
    x = x + 1
end
print(sum)
for
-- 基本结构
for var=m,n,step do
    ....
end
-- 数字型 for(numeric for)
for var = begin, finish, step do
    --body
end
-- 范型 for(generic for)
local a = {"a", "b", "c", "d"}
for i, v in ipairs(a) do
  print("index:", i, " value:", v)
end
常见的迭代器:
- 迭代文件中每行的(io.lines)
- 迭代 table元素的(pairs)
- 迭代数组元素的(ipairs)
- 迭代字符串中单词的(string.gmatch)
repeat
-- 基本结构
repeat
    ...
until conditions
-- 例如
x = 10
repeat
    print(x)
until false
其他控制
- break 用来终止 while、repeat-until和for三种循环的执行,并跳出当前循环体
- return 用来从函数中返回结果,或用来简单的结束一个函数的执行
- goto LuaJit 扩展的,可以变相实现 continue(Lua 语言没有continue的定义)
- 使用 ::label::便签定义
- 使用 goto label跳转到对应的地方执行
 
优化
- 全局变量查表效率低,使用 local定义局部变量可以加速执行效率