推荐:在线Lua测试 , 免环境搭建
变量
-
默认全局变量
a=1 c,d=1,2
-
局部变量
local a=1
-
nil 没有被声明的变量为nil
-
类型
# 字符串连接: .. c = "aaa".."bbb" # number -> strnig c = tostring(12) # string -> number (转换失败为 nil) n = tonumber("10") # 获取字符串长度 len = #"2345678"
-
函数
fun = function(a,b) -- body return a,b end -- 或(等价于) function fun(a,b) -- body return a,b end -- 调用 return 可以返回多个值 res1,res2 = fun(1,2)
-
table
- 数字下标方式
-- 1. 数字小标 (下标从1开始) === 越界为 nil a={1,'2',{},function() end,2} -- 获取元素 print(a[1]) -- 修改 a[1]=function() return 'xx' end a[8]=21212 -- 插入insert(tableName,item) table.insert(a,'新插入的值') -- 插入insert(tableName,pos,item) 指定位置 table.insert(a,2,'新插入的值-pos-2') -- a[8]=21212 -- a[9]=nil -- a[6]='2' -- a[6]='新插入的值' print(a[8],a[9],a[6], a[7]) -- 移除元素 remove(tableName,index) s=table.remove(a, 1) -- a[1]=新插入的值-pos-2 -- s=function: 0xc7 print(a[1],s) -- -- 获取长度 print("table的长度为:"..tostring(#a) )
- 字符串下标方式
a={ a=1, b='123', c=function() return a['b'] end, d={1,2,3} } -- 获取元素 两种方式 : a[key] 、a.key -- a['c']=a.c=function: 0xc2 print(a['c'],a.c) -- a['c']() ==>123 print(a['c']())
-
全局表 table: _G (存放了所有的全局变量)
--print==> 0x3 print(_G) -- table.insert方法-->_G的table的insert -- 即 _G中有一个名为table类型为table的元素 -- print==>table: 0x10 print(_G['table']) -- 切 _G['table']也为一个 table,并存放了insert 函数类型的元素 --print==> function: 0xc4 print(_G['table'].insert)
-
布尔类型
-- 在lua中,只有 nil 与 false 为假 -- 布尔运算符:not and or (布尔运算符 不一定返回 boolean类型===> 短路运算) t,f=true,false -- false true, false (~= : 为不等于) print(t==f,t~=f, not t) -- print(t>f) -- error -- print ==> 1 , true , 2 print(1 or nil, 0 and true, 1 and 2, nil or 1) -- 实现三元运算法 function fun( condition,resTrue,resFalse) return condition and resTrue or resFalse end print( fun(1<2,true,false) )
分支判断
-
if
-- if===>if + elseif + else -- 实现三元运算法 function fun( condition,resTrue,resFalse) if condition then return resTrue else return resFalse end end print( fun(0,true,false) ) -- true
-
循环
-- 1. for循环 -- for i=初始值,终值,步长(默认为1) 注意: i<=终值 -- for 中的i 不能修改 for i=1,10,2 do if(i==3) then break end print(i) end
-- 2. while 循环 n=10 while n>1 do print(n) n=n-1 end