Lua基础
注释
print("hello.")
-- 单行注释的写法
--[[
多行注释的写法
--]]
标识符
关键字
**and **
break
**do **
else
**elseif **
**end **
false
for
**function **
if
in
local
nil
not
or
repeat
return
then
true
until
**while **
数据类型
nil
** boolean**
** number**
** string**
** function**
** userdata**
thread
** table**
--科学计数法
print(2e+1) -- 2x10^1
print(2e-1)
```lua
–string
print(“hello”…“world”);
print(“1”…“2”)
print(type(“1”…“2”)) – 12 string
print(“1”+“2”)
print(type(“1”+“2”)) --3 number
--tabletable1 = {} --空表
table2 = {f1 = 100,key2 = "value"}print(table1)
print(table2.f1)
print(table2.key2)
print(table2["key2"])--使用索引来获取
fruits = {"apple","pear","oranger"}
for i,j in pairs(fruits) doprint(i.."|"..j)
end
print(fruits[1])
print(fruits[2])
print(fruits[3])--table是自动扩容的fruits[1] = "newApple"
print(fruits[1])
table的索引是从1开始
函数
--函数
--函数function fact(n)if n == 1 thenreturn nelsereturn n*fact(n-1)end
endprint(fact(5))function ReadMap(table,func)for k,v in pairs(table) dofunc(k,v)end
endfunction func(k,v)print("key: "..k)print("value: "..v)
endfruits = {apple = 5,banana = 10,watermelon = 20}
ReadMap(fruits,func)
匿名函数
myprint = function(param)printFunc(param)
endfunction printFunc(param)print("打印:"..param)
endmyprint(90)
param : 里面是一个table
变量
lua中变量的类型是可以更改的
a = 5 -- 全局变量
print(type(a))a = "hello World"
print(type(a))dolocal b = 10print(a)print(b) -- 10
endprint(a)
print(b) -- nil
多变量赋值
function test(a,b)return a,b
enda,b = test(1,2)
print(a..b)
循环
a = 0
while(a < 5) doif(a%2 == 0) thenprint(a)enda = a+1
end
for i=0,10,1 doprint(i)
end--repeati = 2
repeatprint(i)i = i*2
until(i > 10) --循环截至条件for i =1,10,1 doj=1while j <= i doprint(j)j= j+1end
end
流程控制
a = 7if(a>10) thenprint("a大于10")
elseif a > 5 thenprint("a大于5")
elseif a > 5 thenprint("a大于0")
elseprint("a小于0")
end
运算符
~=不等于
转义字符
字符串操作
str = "My name is huangjiaqi"
str2 = string.upper(str)
str3 = string.gsub(str,"i","I")index = string.find(str,"name")
str4 = string.reverse(str);print(str)
print(str2)
print(str3)
print(index) --索引从1开始
print(str4)
字符串格式化
--字符串格式化num1 = 3 ; num2 = 5
str5 = string.format("加法运算:%d+%d = %d",num1,num2,(num1+num2))
print(str5)