2

是否可以使用Maya Mel 脚本语言创建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;
}

Ps 我试过了,它没有用,但你可能知道另一种选择。

非常感谢

4

1 回答 1

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;
于 2012-01-19T15:04:57.250 回答