Attempt to "go back" without goto statement
The code examples are gonna be in Lua, but the question is rather general
- it's just an example.
for k=0,100 do
::again::
local X = math.random(100)
if X <= 30
then
-- do something
else
goto again
end
end
This code generates 100 pseudorandom numbers between 0-30. It should do it
between 0-100, but doesn't let the loop go on if any of them is larger
than 30.
I try to do this task without goto statement.
for k=0,100 do
local X = 100 -- may be put behind "for", in some cases, the matter is
that we need an 'X' variable
while X >= 30 do --IMPORTANT! it's the opposite operation of the "if"
condition above!
X = math.random(100)
end
-- do the same "something" as in the condition above
end
Instead, this program runs the random number generation until I get a
desired value. In general, I put all the codes here that was between the
main loop and the condition in the first example.
Theoretically, it does the same as the first example, only without gotos.
However, I'm not sure in it.
Main question: are these program codes equal? They do the same? If yes,
which is the faster (=more optimized)? If no, what's the difference?
No comments:
Post a Comment