When I create a lambda, I would like to be able to set values in the method that is outside of it. You need to be able to do this to use lambdas in patterns like visitors. It's also how they work in languages like C++. The below method prints the output 6 5. I want it to print 6 6 - that is, I want to be able to have foo set to the value the lambda sets it to. This value seems to get reverted after the lambda exits.

Is there a way for my lambda to have the value it sets foo to persist?

# Called when the node enters the scene tree for the first time.
func _ready():
	var foo:float = 5
	
	var cb = func():
		foo = 6
		print(str(foo))
	
	cb.call()
	
	print(str(foo))
  • xyz replied to this.

    kitfox Put the variable into an object (array, dict or a custom class).

    In C++ you can choose what outer stuff is passed into lambdas by reference and what's passed by value. Here you can't. It follows immutable passing rules for functions: fundamental types are always passed by value and objects are always passed by reference. So in GDScript you can never pass a naked float into a function by reference, be it lambda or just a regular function.

    Note that from this follows that if you declare your foo as a class property instead of a local variable it will be passed by reference since it's a property of the implicit self object.

    var foo:float = 5
    func _ready():
    	var cb = func():
    		foo = 6
    		print(str(foo))
    	
    	cb.call()
    	
    	print(str(foo))