就如同C里的if else,while,do,repeat。就看lua里怎么用:
1、首先看if else
t = {1,2,3}
local i = 1
if t[i] and t[i] % 2 == 0 then
print("even")
else
print("odd")
end2、while
while t[i] do
print(t[i])
i = i + 1
end
do
print(t[i])
i = i + 1
end
local i = 1
repeat
print(t[i])
i = i + 1
until t[i] == nilfor i = 1, #t do
print(t[i])
end
for k,v in pairs(t) do
print(k , v)
endfor k,v in pairs(t) do
print(k , v)
if k == 2 then
break
end
end1、lua为毛支持elseif这样的写法
比方能够这么写:
for k,v in pairs(t) do
if k == 2 then
print(‘111‘)
elseif k == 1 then
print(k , v)
end
endt = {1,2,3}
for k,v in pairs(t) do
if k == 2 then
print(‘111‘)
else if k == 1 then
print(k , v)
end
end
end
由于lua里没有switch,假设选择分支比較多写那么多end非常丑陋,so就能够elseif一起用啦。
2、写无条件运行代码,假设c里我喜欢用do{}while(false);lua就能够有非常多写法,来个最easy想到的:
local i = 0
repeat
i = i + 1
print(i)
if i > 10 then
break
end
until false4、改动恶心的goto语句,的确看着非常不爽。改了就清爽多了:
function room1()
repeat
local move = io.read()
if move == "south" then
return room3()
elseif move == "east" then
return room2()
else
print("invalid move")
end
until false
end
function room2()
repeat
local move = io.read()
if move == "south" then
return room4()
elseif move == "west" then
return room1()
else
print("invalid move")
end
until false
end
function room3()
repeat
local move = io.read()
if move == "north" then
return room1()
elseif move == "east" then
return room4()
else
print("invalid move")
end
until false
end
function room4()
print("Congratulations, u win!")
end
room1()
goto不能调到某个语句块内。由于内部是不能为外部所知道的。为毛不能跳出函数块,书里的解释是:
stackflow的答案是:
Your guesses are hinting at the answer. The reason is because the?goto?statement
and its destination must reside in the same stack frame. The program context before and after the?goto?need
to be the same otherwise the code being jumped to won‘t be running in its correct stack frame and its behavior will be undefined.?goto?in
C has the same restrictions for the same reasons.
6、这道题看到goto就好凌乱,我压根就打算用goto。也驾驭不了介个,so不分析了。
原文:https://www.cnblogs.com/mqxnongmin/p/10626452.html