a =10local b =0x20--十六进制表示方法
c,d =3e6,1e10--科学计数法
e =tonumber("789")--转换成数字
运算符:
a =2^6--2的6次方
b =2<<3--左移
c =2>>3--右移动
d =true--true或者false,只有false和nil代表假
c =1~=1--不等号
a and b--与运算
a or b--非运算not a--取反
b = b >1and0or1--三元运算
字符串
str1 ="abcd\n"--字符串声明,单引号双引号都可以,支持转义字符
str2 ='abcd'
str3 = str1..str2--字符串拼接
str4 =[[asd1af4a896f416\naf41]]--这种字符串声明方式不会进行转义
str5 =tostring(123)--转换成字符串
len =#str1--获取长度
s = string.char(0x10,0x11,0x12)--[[
ascii转字符串,0x00不会影响字符串长度,也会输出为一个奇怪的字符
]]
n = string.byte(s,2)--取出第二个字符的ascii值--或者可以这么写
n = s:byte(2)--第一个参数会传入冒号前面的变量
函数声明:(类似js)
functionadd(a,b)return a+b
end--可返回多个值
f =function(a,b)return a,b
end
数组:下标从1开始
a ={1,"abc",{2,3}}
b = a[1]
a[5]=5--可以跨下标赋值,但a长度不会变
table.insert(a,8)--从末尾插入
table.insert(a,4,4)--从某个位置插入
table.remove(a,2)--从某个位置移除
a ={11,22,13,41,45,-68}
table.sort(a,function(a,b)return a>b end)--排序(必须是同种类型才行)
表(类似与在里面声明变量,然后归类到一起)_G是全局表,里面包含了所有声明的全局变量
a ={
a=1,
b="123",
c ={1,2,3}}print(a['a'])--可以用变量名访问print(a.a)--可以用.号访问
分支判断与循环
if a>b then...elseif a > c then...else...end--for循环里i为只读for i=1,10do--运行10次,i每次+1...if i>10then--break语句breakendendfor i=1,10,2do--运行5次,i每次+2...endwhile n>1do
n=n-1end
多文件引用
--假设存在test.lua这个文件require("test")--会直接执行test.luarequire("Test.test")--Test目录下的test.lua
ret =require("test")--在test.lua里可以返回值--多次require同一文件只会运行一次--使用方法:--test.lua:local test ={}function test.Add(a,b)return a+b
endreturn test
--main.lua
test =require("test")
test.Add(1,2)