Why does Lua have no “continue” statement?

后端 未结 11 1709
无人及你
无人及你 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:03

    You can wrap loop body in additional repeat until true and then use do break end inside for effect of continue. Naturally, you'll need to set up additional flags if you also intend to really break out of loop as well.

    This will loop 5 times, printing 1, 2, and 3 each time.

    for idx = 1, 5 do
        repeat
            print(1)
            print(2)
            print(3)
            do break end -- goes to next iteration of for
            print(4)
            print(5)
        until true
    end
    

    This construction even translates to literal one opcode JMP in Lua bytecode!

    $ luac -l continue.lua 
    
    main  (22 instructions, 88 bytes at 0x23c9530)
    0+ params, 6 slots, 0 upvalues, 4 locals, 6 constants, 0 functions
        1   [1] LOADK       0 -1    ; 1
        2   [1] LOADK       1 -2    ; 3
        3   [1] LOADK       2 -1    ; 1
        4   [1] FORPREP     0 16    ; to 21
        5   [3] GETGLOBAL   4 -3    ; print
        6   [3] LOADK       5 -1    ; 1
        7   [3] CALL        4 2 1
        8   [4] GETGLOBAL   4 -3    ; print
        9   [4] LOADK       5 -4    ; 2
        10  [4] CALL        4 2 1
        11  [5] GETGLOBAL   4 -3    ; print
        12  [5] LOADK       5 -2    ; 3
        13  [5] CALL        4 2 1
        14  [6] JMP         6   ; to 21 -- Here it is! If you remove do break end from code, result will only differ by this single line.
        15  [7] GETGLOBAL   4 -3    ; print
        16  [7] LOADK       5 -5    ; 4
        17  [7] CALL        4 2 1
        18  [8] GETGLOBAL   4 -3    ; print
        19  [8] LOADK       5 -6    ; 5
        20  [8] CALL        4 2 1
        21  [1] FORLOOP     0 -17   ; to 5
        22  [10]    RETURN      0 1
    

提交回复
热议问题