Continue in Lua

Lua 是没有 continue 关键字的,Lua 的作者 Roberto 在 mail list 提到过原因:

Continue, on the other hand, is a real feature. (It even changes the

syntax and the lexical.)  Our main concern with "continue" is that there

are several other control structures that (in our view) are more or

less as important as "continue" and may even replace it. (E.g., break

with labels [as in Java] or even a more generic goto.) "continue" does

not seem more special than other control-structure mechanisms, except

that it is present in more languages. (Perl actually has two "continue"

statements, "next" and "redo". Both are useful.)

有时候业务需要,就不得不靠我们自己去实现了。先来一个递归版本:

local 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)

优点是逻辑简单明了,缺点就是递归导致的栈溢出问题。再来一个性能优化的版本,也就是再套一层循环:

for i = 1,10 do

    -- 这个 repeat 循环在每个 for 循环下只会跑一次

    repeat

        -- 这个 break 跳出 repeat 循环,相当于 continue 的效果

        if i == 5 then break end

        print(i)

    until true

end

本文分享自微信公众号 - poslua(poslua)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论

暂无评论