Lua支持goto语法, 但是有一定的局限性.
例如
1. 不能在block外面跳入block(因为block中的lable不可见),
2. 不能跳出或者跳入一个函数.
3. 不能跳入本地变量的作用域.
Lua poses some restrictions to where you can jump with a goto. First, labels
follow the usual visibility rules, so you cannot jump into a block (because a
label inside a block is not visible outside it).
Second, you cannot jump out of
a function. (Note that the first rule already excludes the possibility of jumping
into a function.)
Third, you cannot jump into the scope of a local variable.
例子 :
vi lua
i = 0
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit()
end
goto s1
[root@db-172-16-3-150 ~]# lua ./lua
0
1
2
3
但是以上用法在命令行中会失败, 因为命令行中的block和文件不一样, 一个文件就是一个大block(函数例外).
[root@db-172-16-3-150 ~]# lua
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> i = 0
> ::s1:: do
>> print(i)
>> i = i+1
>> end
0
> if i>3 then
>> os.exit()
>> end
> goto s1
stdin:1: no visible label 's1' for <goto> at line 1
在命令行中do end为一个block, 所以后面无法跳入.
goto在Lua中还可用于模拟continue , redo这种用法. 因为Lua目前没有continue和redo的用法.
i = 0
while i<10 do
::redo::
i = i+1
if i%2 == 1 then
goto continue
else
print(i)
goto redo
end
::continue::
end
不能跳入一个本地变量的作用域, 例如 :
[root@db-172-16-3-150 ~]# cat lua
do
goto notok1
local i = 1
print(i)
::notok1:: -- 本地变量的作用域内, 所以无法跳转
i = i+ 1
::ok:: -- 本地变量的作用域结束, 所以可以跳转.
end
报错 :
[root@db-172-16-3-150 ~]# lua ./lua
lua: ./lua:6: <goto notok1> at line 2 jumps into the scope of local 'i'
时间: 2024-09-15 04:59:28