## [SOLVED]Anonymous Function Scope

General discussion about LÖVE, Lua, game development, puns, and unicorns.
rok
Prole
Posts: 36
Joined: Wed Dec 24, 2014 9:12 am
Location: Slovenia

### [SOLVED]Anonymous Function Scope

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 .
Last edited by rok on Tue Jun 30, 2015 9:32 am, edited 1 time in total.

bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

### Re: Anonymous Function Scope

The reason that limitation is there is because there is no good workaround. That said, what are you using string.dump for?

rok
Prole
Posts: 36
Joined: Wed Dec 24, 2014 9:12 am
Location: Slovenia

### Re: Anonymous Function Scope

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.

Xgoff
Party member
Posts: 211
Joined: Fri Nov 19, 2010 4:20 am

### Re: [SOLVED]Anonymous Function Scope

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)

### Who is online

Users browsing this forum: Google [Bot], master both and 22 guests