lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Andreas Falkenhahn wrote:
[...]
My main problem is how to implement a GOSUB that can return to
anywhere in the script (except to functions). The actual jump to the
label's PC is no problem ... that works fine already. The issue is
what information do I need to preserve to be able to return later, e.g.
[...]
With my current implementation, the "gosub label" call does an OP_JMP
to the label's PC, prints "hello", does some stuff and then invokes an OP_JMP
back to "print(k)". But now "k" has an incorrect value!

Well, my initial reaction is that you *can't* --- since k is local to the loop, it's stack slot is going to be reused outside the loop's scope. Imagine this:

local a = 0
for i=0, 10 do a = a + i end
for j=0, 10 do a = a * i end
local k = a

The compiler will probably turn this into something similar to:

_s0 = 0
for _s1=0, 10 do _s0 = _s0 + _s1 end
for _s1=0, 10 do _s0 = _s0 * _s1 end
_s1 = s0

Note that i, j and k all share the same stack slot!

Any language that puts variables on the stack is going to suffer from this problem if you try to jump from one scope into another. C suffers from this, and the compiler will whine at you if you try.

I think you only have two real options: either (a) don't put variables on the stack, putting all your state into globals --- which is slow, and Lua doesn't really support this (loop variables are implicitely local), or (b) try and find some way of converting your GOSUB subroutines into proper functions.

--
[insert interesting .sig here]