break,return 和 goto

    break

    在实际应用中,break 经常用于嵌套循环中。

    return

    return 主要用于从函数中返回结果,或者用于简单的结束一个函数的执行。
    关于函数返回值的细节可以参考 章节。return 只能写在语句块的最后,一旦执行了 return 语句,该语句之后的所有语句都不会再执行。若要写在函数中间,则只能写在一个显式的语句块内,参见示例代码:

    1. local function add(x, y)
    2. return x + y
    3. --print("add: I will return the result " .. (x + y))
    4. --因为前面有个return,若不注释该语句,则会报错
    5. end
    6. local function is_positive(x)
    7. if x > 0 then
    8. return x .. " is positive"
    9. else
    10. return x .. " is non-positive"
    11. end
    12. --,但是不会被执行,此处不会产生输出
    13. print("function end!")
    14. end
    15. local sum = add(10, 20)
    16. print("The sum is " .. sum) -->output:The sum is 30
    17. local answer = is_positive(-10)
    18. print(answer) -->output:-10 is non-positive

    goto

    LuaJIT 一开始对标的是 Lua 5.1,但渐渐地也开始加入部分 Lua 5.2 甚至 Lua 5.3 的有用特性。
    goto 就是其中一个不得不提的例子。

    有了 goto,我们可以实现 continue 的功能:

    1. for i=1, 3 do
    2. if i <= 2 then
    3. print(i, "yes continue")
    4. goto continue
    5. end
    6. print([[i'm end]])
    7. end

    GotoStatement 这个页面上,你能看到更多用 goto 玩转控制流的脑洞。

    goto 的另外一项用途,就是简化错误处理的流程。有些时候你会发现,直接 goto 到函数末尾统一的错误处理过程,是更为清晰的写法。

    1. local function process(input)
    2. print("the input is", input)
    3. if input < 2 then
    4. goto failed
    5. end
    6. -- 更多处理流程和 goto err
    7. print("processing...")
    8. do return end
    9. ::failed::
    10. print("handle error with input", input)
    11. end
    12. process(1)