Continue in Lua
1301285394|%Y-%m-%d|agohover
Lua 是個小巧精美的語言,不過剛上手時,可能會因為它沒有一般語言中的 continue statement 而感到困惑。Lua FAQ 中有做出解釋,考慮如下的 code:
repeat
if cond then continue end
local t = 1
...
until t == 0
由於 continue 會跳過 local t 的宣告,因此後面的 until t == 0 究竟是指全域的 t 或 local t,會顯得語意不明。C++ 也有同樣的問題,因此 C++ 明確規定 do … while() 中的條件式只能參照迴圈外部的變數。
以下是一個取代 continue 的方法:
for i = 1,10 do
repeat -- 這個 repeat 迴圈只會跑一次
-- 這個 break 跳出 repeat 迴圈,相當於 continue 的效果
if i == 5 then break end
print(i)
until true
end
這是另一個帥氣的做法,非常地 functional style:
function foo(i, max)
if i == 5 then
return foo(6, max) -- continue to i=6
end
print(i)
if i == max then
return
else
return foo(i+1, max)
end
end
foo(1, 10)
Comments
page revision: 0, last edited: 28 Mar 2011 04:09
Post preview:
Close preview