Strange / dangerous(?) bug with function optional arguments

function:
function testfunc( p1, p2, o1, o2 )
{
var v1 = 5;
var v2 = 6;

Sys.println( " ---- " + p1 + " ; " + p2 + " ; " + o1 + " ; " + o2 + " ; " + v1 + " ; " + v2 + " ---- ");
}


call1:
testfunc(1, 2, 3, 4);

Output: " ---- 1 ; 2 ; 3 ; 4 ; 5 ; 6 ---- "

call2:
testfunc(1, 2);

Output: " ---- 1 ; 2 ; null ; null ; 5 ; ---- "

In second case, with calling testfunc() without all arguments, it damage the variable value inside the function. The value of v2 is not 6!

I test it only in Simulator, not at a real device.
  • As far as I can tell, MonkeyC does not support optional arguments directly. It allows you to call functions with the incorrect number of arguments, but it doesn't appear to be part of the language specification.

    If you want to have optional arguments, pack them into a Dictionary, pass them in, and unpack them inside.

    Travis
  • Former Member
    Former Member over 10 years ago
    Not sure if it's intentional but I did find it could handle a single optional argument ok, but only 1. You can then also test for that variable. Eg function sample(variable){
    if(null != optionalVariable){
    // ....
    }
    var passed = variable;
    // ....
    }
  • The implementation doesn't say that it does or does not support optional arguments. Until someone at Garmin says otherwise, it is probably best to consider this to be undefined behavior. It may work in some cases, and it may explode in others.
  • Thanks for the catch--I'll look into this and get it reported.