optional parameters / arguments - how to
Monkey Forums/Monkey Programming/optional parameters / arguments - how to
| ||
How do i set optional parameters when i call a method? Thanks. |
| ||
[monkeycode]Function Main() Foo() ' prints "a=1, b=2, c=bar" Foo(5) ' prints "a=5, b=2, c=bar" Foo(,1) ' prints "a=1, b=1, c=bar" Foo(,,"hello") ' prints "a=1, b=2, c=hello" End Function Foo:Void(a:Int=1, b:Int=2, c:String="bar") Print "a="+a+", b="+b+", c="+c End[/monkeycode] |
| ||
For prevention of headsplosion, never use optional parameters where commas will be needed ;-) At least that's my motto. |
| ||
I thought about it, and basically i want to send anywhere form 0 to many pieces of data when i create an instance. And to do so i may just need to send an StringMap that contains the extra information. So ill try that. Thanks. |
| ||
Depending on the type of data you want to pass to the method, you might be able to use an array []. [monkeycode] Function Main() Foo( [ "hello", "world" ] ) End Function Function Foo( arr : String[] = [] ) For Local index : Int = 0 Until arr.Length Print arr[ index ] Next End Function [/monkeycode] |
| ||
The kind of data i want to pass will end up stored in a StringMap. Stuff like color:blue, health:10, range:5 ect. I'm having trouble finding out how to send a StringMap to a Method, could anyone give me an example of how it is written properly? What i have tryed is a variety of code that looks like this: |
| ||
[monkeycode] Import mojo Function Main() Local data : StringMap< StringObject > = New StringMap< StringObject > data.Add( "Name", "Hero" ) MakeUnit( data ) End Function Function MakeUnit( data : StringMap< StringObject > ) Print(data.Get( "Name" ) End Function [/monkeycode] hope that helps :) |
| ||
Don't go creating StringMaps constantly though. Frequent garbage collection will kill your app (especially on Android). Reuse them if you can. |
| ||
Wow i don't know how many time i tried but i never got it to work :) Thanks NoOdle. I am struggling a bit with Monkey Syntax in some ways, but i have always struggle with Syntax in a language. Samah, do you mean i should not choose a local StringMap for a method call i will use allot, and instead i should use a Field StingMap and clear it when i am done? Or do you mean i should not use a StringMap when i call a method at all? Thanks guys! =) |
| ||
Samah, do you mean i should not choose a local StringMap for a method call i will use allot, and instead i should use a Field StingMap and clear it when i am done? Yep. :) |
| ||
Hi, Also, you don't need to use StringMap<StringObject> any more - just StringMap<String> should do the trick. |