Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't gotos in Lua jump out of functions?

Tags:

lua

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:

  • If you jump from one function into another and the second one returns, where does the PC go?
  • If you have a = f() but f does a goto to after that line of code, what is the value of a?
  • Is it not possible to define a standard behaviour because of different platforms' calling conventions?

I wonder how the author would answer that question. Maybe I'll e-mail him.

In the meantime, does anybody else have some ideas?

like image 535
Nicolas Louis Guillemot Avatar asked Sep 05 '13 21:09

Nicolas Louis Guillemot


1 Answers

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.

like image 129
jdb Avatar answered Jan 03 '23 02:01

jdb