Lua goto 语句

Lua 条件语句Lua 循环语句

Lua 语言中的 goto 语句允许将控制流程无条件地转到被标记的语句处。

 

1. Lua goto 语句的语法

语法格式如下所示:

goto Label

Label 的格式为:

:: Label ::

 

2. Lua goto 语句的范例

local a = 1
::label:: print("--- goto label ---")

a = a+1
if a < 3 then
    goto label   -- a 小于 3 的时候跳转到标签 label
end

输出结果为:

--- goto label ---
--- goto label ---

从输出结果可以看出,多输出了一次 --- goto label ---

以下范例演示了可以在 lable 中设置多个语句:

i = 0
::s1:: do
  print(i)
  i = i+1
end
if i>3 then
  os.exit()   -- i 大于 3 时退出
end
goto s1

输出结果为:

0
1
2
3

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

for i=1, 3 do
    if i <= 2 then
        print(i, "yes continue")
        goto continue
    end
    print(i, " no continue")
    ::continue::
    print([[i'm end]])
end

输出结果为:

1   yes continue
i'm end
2   yes continue
i'm end
3    no continue
i'm end

Lua 条件语句Lua 循环语句

Lua I/O 库用于读取和处理文件。分为简单模式、完全模式。简单模式(simple model)拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作。完全模式(complete model) 使用外部的文件句柄来实现。它以一种面对对象的形式,将所有的文件操作定义为文件句柄的方法。