About Monkey 2 › Forums › Monkey 2 Programming Help › Local scope lambdas
This topic contains 6 replies, has 5 voices, and was last updated by
cocon 2 years, 8 months ago.
-
AuthorPosts
-
August 5, 2016 at 2:46 am #2765Monkey1234567891011121314Function Main()Local add := Lambda:Int(a:Int, b:Int)Return a + bEndLocal str:StringLocal append := Lambda(s:String)' Error : Value 'str' is not assignable'str += ", " + sEndPrint(add(10, 10))End
I would like to know how I can reference str variable inside the append lambda.
August 5, 2016 at 2:57 am #2766You need to declare ‘str’ before the lamba, not after.
August 5, 2016 at 10:01 am #2782Mark, I think he did, or? He got the error inside the append function.
August 5, 2016 at 12:04 pm #2785Yeah, the relevant code is:
Monkey12345678910Function Main()Local str:StringLocal append := Lambda(s:String)str += ", " + sEndEndDon’t know much about lambdas in practice, but that to me looks like it ‘should’ work.
August 5, 2016 at 6:15 pm #2798I’m not sure what the variable scope is when it comes to lambdas in monkey 2, I know that would work in javascript, but it’s probably out of scope here, unless it’s a bug…
August 5, 2016 at 7:31 pm #2806Forgot to also mention, you cannot modify ‘captured’ variables inside a lambda, ie: this should give an error:
Monkey123456Function Test()Local t:=0Local f:=Lambda()t=1 'Error! 't' cannot be modified here.EndEndA lambda effectively gets a ‘copy’ of outer locals at the time the lambda is evaluated. So this..
Monkey12345678Function Test()Local t:=0Local f:=Lambda()Print tEndt=1f()End…will print ‘0’.
August 6, 2016 at 2:22 pm #2831The ideal lambdas have the function purity concept (that no data modifications are allowed). I don’t know if Monkey uses that design indeed.
What I had more in mind was the C# concept of Action and Func that modify variables. Perhaps C++ as well by using the ampersand operator.
-
AuthorPosts
You must be logged in to reply to this topic.