Luagotoの使用例



Lua Goto Usage Example



Luaはgoto構文をサポートしていますが、いくつかの制限があります。例1.ブロックの外側のブロックにジャンプできない(ブロック内のラベルが表示されていないため)、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@xxxxx ~]# lua ./lua 0 1 2 3
ただし、コマンドラインのブロックとファイルが同じではないため、上記の使用法はコマンドラインで失敗します。ファイルは大きなブロックです(関数の例外)。
[root@xxxxx ~]# 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 at line 1
コマンドラインでは、do endはブロックであるため、後でジャンプすることはできません。 GotoをLuaで使用して、続行、やり直しの使用をシミュレートすることもできます。 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@xxxxx ~]# cat lua do goto notok1 local i = 1 print(i) ::notok1:: -- within the scope of the local variable, so can't jump i = i+ 1 ::ok:: -- The scope of the local variable ends, so you can jump. end Error: [root@xxxxx ~]# lua ./lua lua: ./lua:6: at line 2 jumps into the scope of local 'i'