In Lua, are these two snippets exactly equivalent?
repeat
...
until <condition>
while true do
...
if <condition> then break end
end
At first glance they seem to be equivalent - and I believe they are even in corner cases, for example:
Lua evaluates
until <condition>
in the scope of the loop body. (Unlike in C, where a similar pair ofdo
/while
andwhile
loops would not be equivalent because C evaluates the condition in the outer scope.)Lua doesn't have
continue
, which would jump tountil <condition>
in the first loop andwhile true
in the second.
However, are there any other corner cases where they behave differently? Or are they exactly equivalent?
In Lua, are these two snippets exactly equivalent?
repeat
...
until <condition>
while true do
...
if <condition> then break end
end
At first glance they seem to be equivalent - and I believe they are even in corner cases, for example:
Lua evaluates
until <condition>
in the scope of the loop body. (Unlike in C, where a similar pair ofdo
/while
andwhile
loops would not be equivalent because C evaluates the condition in the outer scope.)Lua doesn't have
continue
, which would jump tountil <condition>
in the first loop andwhile true
in the second.
However, are there any other corner cases where they behave differently? Or are they exactly equivalent?
Share Improve this question edited Mar 25 at 19:04 user200783 asked Mar 25 at 10:43 user200783user200783 14.4k15 gold badges79 silver badges142 bronze badges 3 |1 Answer
Reset to default 0The bytecode is almost identical in both cases (using Lua 5.4.7):
% cat 1
local a,b
repeat
a()
until b()
% luac -l 1
main <1:0,0> (9 instructions at 0x7f842d406230)
0+ params, 3 slots, 1 upvalue, 2 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADNIL 0 1 ; 2 out
3 [3] MOVE 2 0
4 [3] CALL 2 1 1 ; 0 in 0 out
5 [4] MOVE 2 1
6 [4] CALL 2 1 2 ; 0 in 1 out
7 [4] TEST 2 0
8 [4] JMP -6 ; to 3
9 [4] RETURN 2 1 1 ; 0 out
% cat 2
local a,b
while true do
a()
if b() then break end
end
% luac -l 2
main <2:0,0> (10 instructions at 0x7fa46dc06230)
0+ params, 3 slots, 1 upvalue, 2 locals, 0 constants, 0 functions
1 [1] VARARGPREP 0
2 [1] LOADNIL 0 1 ; 2 out
3 [3] MOVE 2 0
4 [3] CALL 2 1 1 ; 0 in 0 out
5 [4] MOVE 2 1
6 [4] CALL 2 1 2 ; 0 in 1 out
7 [4] TEST 2 1
8 [4] JMP 1 ; to 10
9 [4] JMP -7 ; to 3
10 [5] RETURN 2 1 1 ; 0 out
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744203181a4562977.html
continue
then should you be concerned aboutgoto
(lua-users./wiki/GotoStatement ) as well? – Richard Chambers Commented Mar 25 at 19:14goto
s and labels inside the...
would behave the same in both cases – user200783 Commented Mar 25 at 19:19