Search code examples
mayamel

Switch statement using variables in the case condition


Is it possible to create Switch statements that use variables in the case condition, in Maya Mel Script language?

Something along the lines (stupid example for the sake of explanation):

$val1 = "foo";
$val2 = "bar";
// imagine $input as an argument of some proc
switch ($input)
{
case $val1:
    print "Input is 'foo'";
    break;

case $val2:
    print "Input is 'bar'";
    break;
}

P.s. I tried that and it didn't work, but you might know of another option.

Thanks a lot


Solution

  • You can't use variables as case values directly, but you can build a string containing the code that you want to execute, with variables replaced with their values, and pass that string to the eval function:

    $val1 = "foo";
    $val2 = "bar";
    // imagine $input as an argument of some proc
    string $cmd;
    $cmd =  "switch (\"" + $input + "\")";
    $cmd += "{";
    $cmd += "case \"" + $val1 + "\":";
    $cmd += "    print \"Input is 'foo'\";";
    $cmd += "    break;";
    $cmd += "case \"" + $val2 + "\":";
    $cmd += "    print \"Input is 'bar'\";";
    $cmd += "    break;";
    $cmd += "}";
    eval $cmd;