Why does Lua have no “continue” statement?

后端 未结 11 1708
无人及你
无人及你 2020-12-07 13:23

I have been dealing a lot with Lua in the past few months, and I really like most of the features but I\'m still missing something among those:

  • Why is there no
11条回答
  •  星月不相逢
    2020-12-07 14:10

    We encountered this scenario many times and we simply use a flag to simulate continue. We try to avoid the use of goto statements as well.

    Example: The code intends to print the statements from i=1 to i=10 except i=3. In addition it also prints "loop start", loop end", "if start", and "if end" to simulate other nested statements that exist in your code.

    size = 10
    for i=1, size do
        print("loop start")
        if whatever then
            print("if start")
            if (i == 3) then
                print("i is 3")
                --continue
            end
            print(j)
            print("if end")
        end
        print("loop end")
    end
    

    is achieved by enclosing all remaining statements until the end scope of the loop with a test flag.

    size = 10
    for i=1, size do
        print("loop start")
        local continue = false;  -- initialize flag at the start of the loop
        if whatever then
            print("if start")
            if (i == 3) then
                print("i is 3")
                continue = true
            end
    
            if continue==false then          -- test flag
                print(j)
                print("if end")
            end
        end
    
        if (continue==false) then            -- test flag
            print("loop end")
        end
    end
    

    I'm not saying that this is the best approach but it works perfectly to us.

提交回复
热议问题