Lua支持一组几乎传统的语句,类似于C或Pascal。传统的报表包括任务,控制结构,和过程调用。Lua还支持一些不那么传统的语句,如多重赋值和局部变量声明。
4.1 赋值
Lua允许多重赋值:a, b = 10, 2*x
结果是a = 10,b = 2*x
x,y = y,x
结果是x和y交换值
4.2局部变量和块
在一个全局变量前面添加local就变成局部变量
local i = 1 – local variable
x = 10
local i = 1 -- local to the chunk
while i <= x do
local x = i*2 -- local to the while body
print(x) --> 2, 4, 6, 8, ...
i = i + 1
end
20 then
local x -- local to the "then" body
x = 20
print(x + 2) -- (would print 22 if test succeeded)
else
print(x) --> 10 (the global one)
end
print(x) --> 10 (the global one)
显式定义程序块:
do
local a2 = 2*a
local d = (b^2 - 4*a*c)^(1/2)
x1 = (-b + d)/a2
x2 = (-b - d)/a2
end -- scope of 'a2' and 'd' ends here
print(x1, x2)
print(d) -- nil
4.3控制结构
以end 结束的有 if, for and while 结构; 以until 结束的有 repeat
另外Lua不支持switch语句
if then else:
if a < 0 then a = 0 end
if a < b then return a else return b end
if line > MAXLINES then
showpage()
line = 0
end
while
local i = 1
while a[i] do
print(a[i])
i = i + 1
end
repeat
repeat
line = io.read()
until line ~= ""
print(line)
Numeric for
for var = exp1, exp2, exp3 do
<something>
end
generic for
for k, v in pairs(t) do print(k, v) end
4.4 break, return, and goto控制结构
break和return跳出一个程序块,一般是最后一句
goto用法:
c = 12
goto s1
::s1:: do
if c == 13 then goto s2
elseif c == nil then print'ok'; return
else c = 13
goto s1
end
end
::s2:: do
if c == 12 then goto s1
elseif c == nil then print'not ok'; return
else
print("13right")
end
end