hishamhm/f-strings

Use debug.getupvalue instead of debug.getlocal

daurnimator opened this issue · 5 comments

@hishamhm as my comment at http://hisham.hm/2016/01/04/string-interpolation-in-lua/comments/#comment160104-124302 said:

You could use debug.getupvalue instead of iterating up the stack.

This should also fix #1.

Ah, I see the need for debug.getupvalue now... but that's needed in addition to debug.getlocal right? We need to support both upvalues and locals.

I'm not sure.... I was playing around with it a bit last night. but I could never come up with anything that passed all my tests: https://github.com/daurnimator/f-strings/blob/master/spec/F_spec.lua

I finally understood what you meant. Upvalues do collect all upper relevant scopes. And what I had implemented before essentially amounted to Lisp-style dynamic scoping:

local F = require("F")
local x = "foo"
local f = function() 
   print(F"{x}")
end
local g = function(fff)
   local x = "bar"
   fff()
end
g(f)

This printed "bar"!

This is now fixed. The above code, unfortunately, now prints nil, because x is unreferenced. But that's beyond what we can do... :\

I pushed f-strings 0.2 to LuaRocks!

Yep. looks like there's no way to handle otherwise unreferenced upvalues.
I can't even think of a suitable modification to lua that would make it work either.