Page 1 of 1

[SOLVED]Anonymous Function Scope

Posted: Tue Jun 30, 2015 7:21 am
by rok
Yesterday a guy on IRC explained to me why this works

Code: Select all

function templates.text(text)
  tmp = text
  return string.dump(function()
    love.graphics.printf(tmp,40,40,400)
  end)
end
but this doesn't

Code: Select all

function templates.text(text)
  return string.dump(function()
    love.graphics.printf(text,40,40,400)
  end)
end
because of the anonymous function scope.

Is there a way to do it without that stupid temporary variable? It even can not be local so that is another problem (overwriting data). There must be a way :cry:.

Re: Anonymous Function Scope

Posted: Tue Jun 30, 2015 8:14 am
by bartbes
The reason that limitation is there is because there is no good workaround. That said, what are you using string.dump for?

Re: Anonymous Function Scope

Posted: Tue Jun 30, 2015 9:31 am
by rok
Oh ok. Changed the code a bit and now I do not need it anymore. I've been using string.dump in pair with loadstring.

Returning the function directly instead of the string representation solved the scope issue too. Double win.

Re: [SOLVED]Anonymous Function Scope

Posted: Tue Jun 30, 2015 3:20 pm
by Xgoff
yes, whenever possible you should return functions instead of dumping/loading them

for informational purposes: in lua 5.2/5.3 or luajit, it is in fact possible to "fix" upvalue bindings of loaded functions via debug.upvalueid and debug.upvaluejoin, but obviously you should only be doing things like that if you absolutely cannot avoid dumping/loading the function (such as trying to send a function between love threads, since iirc you can't send function objects)