Lua语法入门

之前在用vim的时候发现很多插件的配置文件是用Lua写的,还是挺想了解一下的。

变量

默认全局变量,即在另一个文件中也可以使用

1
2
3
a = 1
local b = 2
a,b = 1,2 //多重赋值

nil

类似于NULL,没有被声明的变量都是nil

数值型

只有number类型

1
2
a = 0x11 
b = 2e10

运算符

1
2
3
print(a + b)
print(10^5)
print(1 << 3)

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a = "asdfasfasdf\n" //可用转义
b = 'asdfasdfasd'
c = [[
adsfasdfasdfadf
asdfasdfasdfasdf
]] // 多行字符串

d = a..b //两个字符串连接

e = tostring(10)
n = tonumber("10") //若转换失败,则为nil


s = string.char(0x30,0x31,0x32,0x33)
n = string.byte(s,2) // 起始下标是1
print(n)

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function function_name(...)
--body
end

f = function(a,b) //也可以这么写
print(a,b)
end

f(1,2)

function f(a,b,c)
return a,b //默认返回nil,可以返回多个
end


table

1
2
3
4
5
6
7
8
9
// 数字下标
a = {1, "ac", {}, fucntion() end} //下标从1开始
print(a[1])

print(#a) //获取长度

table.insert(a, 2, "d")
local s = table.remove(a, 2) //移除会返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 字符串下标
a = {
a = 1,
b = "1234",
c = function()
print("hello")
end,
d = 123123

[",;"] = 123 // 可以用这种方式用不规范的下标

}
print(a["a"]) // 用双引号
print(a.b) // 若命名规范也可使用.运算符

全局表

1
2
3
所有的全局变量都在 _G 里面
a = 1
print(_G["a"])

真假

1
2
3
4
5
6
7
8
9
a = true
b = false
print(1~=2) //不等于不是!=
a and b
a or b
not a

0 代表真 nil才代表假

分支判断

1
2
3
4
5
6
7
if 1 > 10 then
print("1>10")
elseif 1 < 10 then
print("1<10")
else
print("no")
end

循环

1
2
3
4
5
6
7
8
9
10
11
for i = 1, 10, 2 do //可以多一个步长参数
print(i)
if i == 5 then break end
end

local n = 10
while n > 1 do
print(n)
n = n - 1
end

作者

Jhuoer Yen

发布于

2024-03-04

更新于

2024-03-20

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×