Lua 提供了多种流程控制结构,包括条件语句、循环结构和异常处理。以下是 Lua 中常见的流程控制语句:

1. 条件语句:

if 语句:
local x = 10

if x > 0 then
    print("x is positive")
elseif x < 0 then
    print("x is negative")
else
    print("x is zero")
end

2. 循环结构:

while 循环:
local i = 1

while i <= 5 do
    print(i)
    i = i + 1
end

for 循环:
for i = 1, 5 do
    print(i)
end

repeat...until 循环:
local i = 1

repeat
    print(i)
    i = i + 1
until i > 5

3. 跳转语句:

break 语句:

用于跳出当前的循环。
for i = 1, 5 do
    if i == 3 then
        break
    end
    print(i)
end

goto 语句:

goto 语句用于跳转到指定标签的位置。在 Lua 中,goto 通常用于模拟 continue。
for i = 1, 5 do
    if i == 3 then
        goto continue
    end
    print(i)

    ::continue::
end

4. 异常处理:

pcall 和 assert:

pcall 用于捕获错误并继续执行。
local status, result = pcall(function()
    error("This is an error")
end)

if not status then
    print("Error: " .. result)
end

assert 用于判断一个条件是否为真,如果不为真,则抛出错误。
local x = 10
assert(x > 0, "x must be positive")

这些是 Lua 中常见的流程控制语句。通过合理使用这些语句,你可以实现对程序流程的灵活控制。在实际开发中,了解这些流程控制结构的使用场景将帮助你更好地构建程序逻辑。


转载请注明出处:http://www.zyzy.cn/article/detail/6490/Lua