语句 break 用来终止 while、repeat 和 for 三种循环的执行,并跳出当前循环体, 继续执行当前循环之后的语句。下面举一个 while 循环中的 break 的例子来说明:
-- 计算最小的 x,使从 1 到 x 的所有数相加和大于 100
sum = 0
i = 1
while true do
sum = sum + i
if sum > 100 then
break
end
i = i + 1
end
print("The result is " .. i) -->output:The result is 14
local function add(x, y)
return x + y
--print("add: I will return the result " .. (x + y))
--因为前面有个return,若不注释该语句,则会报错
end
local function is_positive(x)
if x > 0 then
return x .. " is positive"
else
return x .. " is non-positive"
end
--由于return只出现在前面显式的语句块,所以此语句不注释也不会报错,
--但是不会被执行,此处不会产生输出
print("function end!")
end
local sum = add(10, 20)
print("The sum is " .. sum) -->output:The sum is 30
local answer = is_positive(-10)
print(answer) -->output:-10 is non-positive
有时候,为了调试方便,我们可以在某个函数的中间提前 return,以进行控制流的短路。此时我们可以将 return 放在一个 do ... end 代码块中,例如:
local function foo()
print("before")
do return end
print("after") -- 这一行语句永远不会执行到
end
local function process(input)
print("the input is", input)
if input < 2 then
goto failed
end
-- 更多处理流程和 goto err
print("processing...")
do return end
::failed::
print("handle error with input", input)
end
process(1)
process(3)