Fundamentally Lua's built-in loop constructs are all the same; they all boil down to a conditional jump at the machine code level. In fact, all of the loops can be constructed as composites of if...then and repeat...until statements. For instance,
while condition do
do_stuff()
endis exactly the same as
if condition then
repeat
do_stuff()
until not condition
endand a for loop can be similarly deconstructed.
for k, v in pairs(t) do
print(k, v)
endcan be deconstructed into
do
local iter = pairs(t)
local k, v = iter()
if k ~= nil then
repeat
print(k, v)
k, v = iter()
until k == nil
end
endSimilarly,
for i = s, e, inc do
print(i)
endcan be deconstructed as
do
local i = s
local _e = e
local _inc = inc
local _done
if _inc > 0 then
_done = i >= _e
else
_done = i <= _e
end
if not _done then
repeat
print(i)
i = i + _inc
if _inc > 0 then
_done = i >= _e
else
_done = i <= _e
end
until _done
end
endThese are the kinds of deconstructions that are done by the compiler automatically at runtime, so they really are all built from the same fundamental building blocks. The different loops are just there to provide syntactic convenience. They will all block the game.