Reputation: 1628
From the Programming In Lua book 3rd edition page 38
Exercise 4.5: Can you explain why Lua has the restriction that a
goto
cannot jump out of a function? (Hint: how would you implement that feature?)
I have a few guesses as to why it may be so:
a = f()
but f does a goto
to after that line of code, what is the value of a
?I wonder how the author would answer that question. Maybe I'll e-mail him.
In the meantime, does anybody else have some ideas?
Upvotes: 6
Views: 2677
Reputation: 559
Your guesses are hinting at the answer. The reason is because the goto
statement and its destination must reside in the same stack frame. The program context before and after the goto
need to be the same otherwise the code being jumped to won't be running in its correct stack frame and its behavior will be undefined. goto
in C has the same restrictions for the same reasons.
The C standard library also provides longjmp()
and setjump()
which do allow you to implement a form of "goto" out of the current stack frame. setjmp()
saves the current stack context. You can then call longjmp()
to unwind the stack back to where you called setjmp()
. You cannot call longjmp()
after the function which called setjump()
exits.
Upvotes: 10