lua - Lua 语言中 switch 语句的替代方法是什么?

标签 lua switch-statement

我在 C++ 中有这段代码,我想知道如何编写一些代码来替换 Lua 中的 switch 语句,因为我面临很多问题,我需要使用这个语句。

   int choice;
do// loop
{
      cout<<"\n >>> The General Menu <<< \n";
      cout << endl;
    cout<< " press (1) to Add    "<<endl;
    cout<< " press (2) to Save   "<<endl;
    cout<< " press (3) to Quit " << endl;
    cout<< endl;
      cout<< "Enter your choice please (1/2/3): ";
    cin>>choice;

    switch(choice)
    {
        case 1: 
            add();
            break;
        case 2:
            save();
            break;

        default:
            cout<<" The program has been terminated "<<endl;
           cout<<" Thank you! \n";          
    }   
} while (choice != 3);

}
该语句已在 do..while 循环中使用。

最佳答案

一般来说,如果你想在 Lua 中使用 switch 语句,你应该做的是建表。对于您的 choice 的简单案例可能是 1、2 或失败,一个简单的 if有几个条件的语句就足够了。对于更复杂的情况,应使用函数表:

local c_tbl =
{
  [1] = add,
  [2] = save,
}

local func = c_tbl[choice]
if(func) then
  func()
else
  print " The program has been terminated."
  print " Thank you!";
end

您可以使用词法范围来允许表中的函数能够访问局部变量,就像代码是内联编写的一样。

关于lua - Lua 语言中 switch 语句的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37447704/

相关文章:

java - 是否可以访问用户数据属性和函数?

lua - 我传递给 lua 脚本的参数为零

c++ - 在开关盒内阻塞

android - 温泉开关触发回调的问题

Lua 5.3 使用 debug.setmetatable 覆盖整数值的 ~ (__bnot) 运算符

variables - 多重分配如何运作?

lua - 如何将表传递给没有第一个元素的函数?

javascript - Switch 语句实现未提供预期行为

c - "for"开关盒内的循环不起作用

c++ - switch语句默认范围?