在case条件中使用变量切换语句

时间:2011-11-22 11:45:11

标签: maya mel

是否可以使用Maya Mel Script语言创建使用Switch条件中的变量的case语句?

一些事情(为了解释起见的愚蠢的例子):

$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。我试过了它并没有用,但你可能知道另一种选择。

非常感谢

1 个答案:

答案 0 :(得分:2)

您不能直接将变量用作案例值,但您可以构建一个包含要执行的代码的字符串,并将变量替换为其值,并将该字符串传递给eval函数:

$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;