Similar functionallity as JavScript functions/closures "direct calling"

Don’t know the real name for the functionallity in JavaScript, but it’s used like this e.g.

[javascript]
var myObj = {};
myObj.myVariable = (function()(
// … do stuff
return someObj;
}());
[/javascript]

the myObj.myVariable gets whatever value is returned without me ever having to call some function or initialize it myself.

Now to my question: Is it possible do achieve the same effect in Lua? So when I want to use a variable, its value comes from a function that’s “pre-run” and the variable already has its value.

[import]uid: 43027 topic_id: 8001 reply_id: 308001[/import]

Yes, there is :slight_smile:

I’ll answer this one myself as I just got it to work :slight_smile:

[lua]player.healthBar = (function()
local rect = display.newRect(player.x - (player.width / 2), player.y - (player.height / 2) - 8, player.width, 5);
rect:setFillColor(0, 255, 0);
rect:setStrokeColor(0, 0, 0);
rect.strokeWidth = 1;
return rect;
end)();[/lua] [import]uid: 43027 topic_id: 8001 reply_id: 28485[/import]

thanks for sharing.

I’m not sure if anonymous closures get garbage collected well. you’re basically creating a new function each time you call .healthBar i think. I don’t think that’s as optimized as a local setHealth function, but I couldn’t say for sure

might be worth doing some tests

j
[import]uid: 6645 topic_id: 8001 reply_id: 28912[/import]

I have no way of telling if the garbage collector is getting that.

I’m still trying to determine if gcinfo() works in Ansca correctly. [import]uid: 20703 topic_id: 8001 reply_id: 30381[/import]

I have no way of telling if the garbage collector is getting that.

I’m still trying to determine if gcinfo() works in Corona correctly. [import]uid: 20703 topic_id: 8001 reply_id: 30382[/import]