Why does Lua have no “continue” statement?

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

    The first part is answered in the FAQ as slain pointed out.

    As for a workaround, you can wrap the body of the loop in a function and return early from that, e.g.

    -- Print the odd numbers from 1 to 99
    for a = 1, 99 do
      (function()
        if a % 2 == 0 then
          return
        end
        print(a)
      end)()
    end
    

    Or if you want both break and continue functionality, have the local function perform the test, e.g.

    local a = 1
    while (function()
      if a > 99 then
        return false; -- break
      end
      if a % 2 == 0 then
        return true; -- continue
      end
      print(a)
      return true; -- continue
    end)() do
      a = a + 1
    end
    

提交回复
热议问题