Re: Dynamic Scope / Continuation Marks

  • From: Brandon Bloom <brandon.d.bloom@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 5 Nov 2016 15:26:32 -0700

Thank you for the suggestion. You did understand the problem correctly.
Unfortunately, that solution won't quite work exactly right.

If the withx call itself is not in tail position, that code will fail to
restore the old value of x. The code after the withx call may depend on the
restored value.

I mentioned Lua 5.2's debug.getinfo with what='t' and istailcall in my
original post, but didn't elaborate because my mail was already getting
quite long. To make that thought explicit, the following seems to work in
PUC Lua 5.2.4:


globalx = 0

function restorex(oldx, ...)
  globalx = oldx
  return ...
end

function withx(x, body)
  local oldx = globalx
  globalx = x
  if debug.getinfo(1, 't').istailcall then
    return body()
  end
  return restorex(oldx, body())
end

function main()
  return withx(1, function()
    return withx(2, function()
      error('show me the stack')
    end)
  end)
end

main()


Unfortunately, LuaJIT doesn't offer the 't' flag for getinfo. Is there
something analogous I can rely on?


On Fri, Nov 4, 2016 at 2:50 PM, Peter Cawley <corsix@xxxxxxxxxx> wrote:

If I understand your problem, your call frame stack ends up looking like:
1. body
2. withx
3. withx
4. withx
...

Frames 2/3/4 only exist to restore the value of globalx, and frames
2/3 are redundant as the value they restore will be overridden by
frame 4. If this understanding is correct, then the following might be
a solution:

function restorex(oldx, ...)
  globalx = oldx
  return ...
end

function withx(x, body)
  local oldx = restorex(x, globalx)
  if (debug.getinfo(2, "f") or {}).func == withx then return body() end
  return restorex(oldx, body())
end


On Fri, Nov 4, 2016 at 9:18 PM, Brandon Bloom <brandon.d.bloom@xxxxxxxxx>
wrote:
Just for curiosity, is x always the same in your recursive calls or you
have different x?

Nope. The recursive calls necessarily create a stack of x values.


Other related posts: