在 case 条件中使用变量的 Switch 语句

发布于 2024-12-17 16:03:12 字数 386 浏览 0 评论 0原文

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

大致的内容(为了解释起见,这是一个愚蠢的例子):

$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我尝试过,但它不起作用,但你可能知道另一种选择。

多谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦 2024-12-24 16:03:12

您不能直接使用变量作为 case 值,但您可以构建一个包含要执行的代码的字符串,并将变量替换为其值,然后将该字符串传递给 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;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文