zan*_*naM 6 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);
Run Code Online (Sandbox Code Playgroud)
该语句已在do..while循环中使用.
Nic*_*las 13
一般来说,如果你想在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
Run Code Online (Sandbox Code Playgroud)
您可以使用词法作用域来允许表中的函数能够访问局部变量,就像代码是内联编写的一样.
cod*_*nio 11
试试这个(单击此处在 Lua 编译器中运行脚本),希望代码是不言自明的;-) 和
类似于相同的伪代码格式..!!
print("enter your choice : ")
mychoice = io.read()
switch = function (choice)
-- accepts both number as well as string
choice = choice and tonumber(choice) or choice -- returns a number if the choic is a number or string.
-- Define your cases
case =
{
[1] = function ( ) -- case 1 :
print("your choice is Number 1 ") -- code block
end, -- break statement
add = function ( ) -- case 'add' :
print("your choice is string add ") -- code block
end, -- break statement
['+'] = function ( ) -- case '+' :
print("your choice is char + ") -- code block
end, -- break statement
default = function ( ) -- default case
print(" your choice is din't match any of those specified cases")
end, -- u cant exclude end hear :-P
}
-- execution section
if case[choice] then
case[choice]()
else
case["default"]()
end
end
-- Now you can use it as a regular function. Tadaaa..!!
switch(mychoice)
Run Code Online (Sandbox Code Playgroud)
路亚:
if choice == 1
then add()
elseif choice == 2
then save()
else print "The program has been terminated\nThank you!"
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21473 次 |
最近记录: |