Skip to main content
GameDev.net gamedev.net
🔒 Locked

Anonymous functions and local variables

Started by MrK45 Jun 24 at 5:58 AM 4 replies 550+ views
Original Post
MrK45
MrK45

I'm trying to use anonymous functions to make code more readable and structured.

But one thing at docs makes me sad:

(https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_anonfunc.html)

It is not yet possible for anonymous functions to access variables declared in the same scope as the function, i.e. they cannot be used as closures.

Is there any chance that local variables become available to use in lambdas?

For example, this code ten times more compact and easier to understand than others without lambda:

void Initialize()
{
    Register reg;
    reg.OnValueUpdated += function(const Value ∈ val)
    {
        ProcessReg(reg);
    };
}

Converting this example to another using globals makes anonymous functions almost not profitable. Nevermind strange symbol in function arguments, it's just code block visualization issue.

Let the power of C++ be with you.
Alan Voren (PlayServ)
Alan Voren (PlayServ)

Closures in a scripting language are harder than they look - you need to decide whether captured variables live on the stack (cheap, but dangerous once the outer scope exits) or get heap-allocated (safe, but requires a real GC story for cycles). AngelScript's reference counting makes the second route painful, which is probably why this has stayed on the wishlist. Worth raising on the forum with a specific capture model in mind rather than asking generally.

None
WitchLord
WitchLord

Alan is right.

I do want to support closures but it is indeed quite complex. I have given it some thoughts and I think I have a viable solution that could be implemented. But I just don't have the time to do it. And there are so many other things that I believe should be prioritized first.


AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - <a href="http://www.angelcode.com/tower" rel
MrK45
MrK45

Thanks for clarifying. It would be nice to see closures in roadmap.

Let the power of C++ be with you.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.