1、连接两个字符串
方法一:
a = "第一个字符串"
b = "第二贵字符串"
c = a..b
print(c)
方法二:此方法在组合大量字符串时效率高
a = "第一个字符串"
b = "第二贵字符串"
c = table.concat({a,b})
print(c)
方法三:
a = "第一个字符串"
b = "第二贵字符串"
c = string.format("%s%s",a,b)
print(c)
2、 全局变量和局部变量
function xiebian(a,b)
local c2 = a^2 +b^2
c = math.sqrt(c2)
return c
end
print(xiebian(3,4))
函数的定义形式:
function 函数名(参数)
...............
end
变量前加上local修饰是局部变量,否则是全局变量。
在你想更好的控制局部变量的作用域时,do语句块是非常好用的:
do
local a,b,c =1,10,3
local a2 = 2*a --a2==2
local d = (b^2 - 4*a*c)^(1/2) --d==
x1 = (-b + d)/a2
x2 = (-b - d)/a2
end -- scope of 'a2' and 'd' ends here
print(x1, x2) --OK
print(a,b,c) --失效了,遇到end,局部变量失效
sqrt数学函数前面需用math调用
3、for循环do
for 变量 = 参数1, 参数2, 参数3 do 循环体 end
参数1为起始值,参数2为结束值,参数3为增加的步长,缺省为1
for i=1,10,2 do
print(i)
end
参数2可以是函数,且只在开始时调用一遍
变量i为局部变量,只在循环体中有效
无限循环:
for i=1,math.huge do
print(i)
end
4、注释
单行注释: 采用--来对注释后面的字符进行注释,类似于 ISO C90之后的 C语言的注释"//"
多行注释:采用--[[" "]]--对来注释,类似于C语言的 "/*" "*/"。
5、 条件分支语句if thenif 条件 then
..
elseif 条件 then
..
else
..
end
注意只需要一个end
6、while...do语句和repeat until语句
while 条件 do
...
end
repeat
..
until 条件