我在 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/