我在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循环中使用。
答案 0 :(得分: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
您可以使用词法作用域允许表中的函数能够访问局部变量,就像代码是内联编写一样。
答案 1 :(得分:2)
的Lua:
if choice == 1
then add()
elseif choice == 2
then save()
else print "The program has been terminated\nThank you!"
end
答案 2 :(得分:2)
试试这个(click here to run the script in a Lua compiler),希望代码不言自明;-)和
类似于伪代码格式.. !!
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)
答案 3 :(得分:1)
另一个版本的切换器(没有将表初始化为变量):
local case=2;
local result=({[1]="case1", [2]="case2", 3="case3"})[case];
print (result); --> case2
答案 4 :(得分:1)
我遇到了带有不同参数的函数的问题-其他答案无法很好地解决这些问题。
我用匿名函数解决了这个问题。
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
this.state={checked: false}
//this.handleCheckedChange = this.handleCheckedChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.formContent = this.display1();
}
handleSubmit(event) {
alert('Your information is: ' + JSON.stringify(this.formContent) + " " + "Please Make Sure To Select From One of The Vacation Options and Activities From Below");
event.preventDefault();}
NumberList1(props) {
let listItems = React.createElement("p", {key: props.id}, props.item.text, React.createElement("input", {
type: "checkbox",
value: "1",
onChange: () => this.setState({checked: true}),
defaultChecked: false
}))
return (
listItems
)
}
display1(){
let props = [{id: 0, text: "City Tours", completed: false},
{id: 1, text: "Sports", completed: false},
{id: 2, text: "Cycling", completed: false},
{id: 3, text: "Museums", completed: false},
{id: 4, text: "Boating", completed: false}];
let listItems = props.map((item) => this.NumberList1({
key: props.id,
item: item}));
return(React.createElement("div", {}, listItems));
}
render() {
//if(this.state.liked == true){
//;}
//'button',{ onClick: () => this.setState({ liked: true }) },"New Zealand",
return (React.createElement("form", {onSubmit: this.handleSubmit, action: 'http://localhost/test.php', method: "get",
className: "todo-list"
},"Select Activities From Below", (this.formContent),React.createElement("br", {}),
React.createElement("input", {type:"submit", value: "Submit"}),
React.createElement("input", {type:"reset", value: "Reset"})))
}
}
const domContainer = document.getElementById("new");
ReactDOM.render(
(e(LikeButton)),
domContainer);
答案 5 :(得分:0)
如果你想将switch作为一个可调用的函数,你可以使用一些有趣的回调功能:
(以下示例是基于变量类型的switch语句,但您可以将表索引转换为您要测试它的任何内容。只需将switch函数的return语句更改为不测试类型(case) )
(这实际上是一个懒惰的表查找,很像Python的字典功能,但每个元素都是一个函数)
#!/usr/bin/lua
-- Callback switch statement:
local function switch(a, case)
-- Local variable instead of function(a) on every case:
local value = a
-- Cases list:
local switchcase = {}
-- Cases:
switchcase["string"] = function()
return (tostring(value) .. " is a string")
end
switchcase["number"] = function()
return tostring(value .. " is a number")
end
switchcase["boolean"] = function()
return (tostring(avalue) .. " is a boolean")
end
return switchcase[type(case)](a)
end
local value = 5
print(switch(value,value)) --> 5 is a number
local value = "test"
print(switch(value,value)) --> test is a string
local value = true
print(switch(value,value)) --> true is a boolean
我不知道这个代码的性能与上面给出的两个答案相比,但是使用局部变量应该使它足够快以便重复使用。如果在全局范围内进行切换功能,它可以成为项目使用的标准功能。
答案 6 :(得分:0)
这是另一个使用loadstring()和表查找的有趣方法。
switch = function(cases,args)
if (cases[args] == nil) then return args else return assert(loadstring ('return ' .. cases[args]))() end
end
local case = 2
local result = switch({
[1] = "2^" .. case,
[2] = string.format("2^%i",case),
[3] = tostring(2^case)
},
case
)
print(result) --> 4
使用此方法有点危险,因为loadstring()类似于Python的eval()函数。
我发现写&#34; function(x)&#34;在Lua wiki提供的示例中的每个案例中。这是一个很好的方式。
&#34;默认&#34;案例是&#34; return args&#34;功能的一部分。
答案 7 :(得分:0)
我使用以下代码:
while true do local tmpswitch1 = exp ; --[[ switch <exp> do ]]
if tmpswitch1 == exp1 then --[[ case <exp1> : ]]
-- do something
break
end ;if tmpswitch1 == exp2 then --[[ case <exp2> : ]]
-- do something
break
end ; --[[ default : ]]
-- do something
break ; end --[[ switch tmpswitch1 ]]
答案 8 :(得分:0)
虽然最简单的方法是创建一个以事例为索引的表,并以函数作为元素,这是最快的方法,但我提出的这种解决方案使IMO具有更好的代码可读性:
function switch(element)
local Table = {
["Value"] = element,
["DefaultFunction"] = nil,
["Functions"] = {}
}
Table.case = function(testElement, callback)
Table.Functions[testElement] = callback
return Table
end
Table.default = function(callback)
Table.DefaultFunction = callback
return Table
end
Table.process = function()
local Case = Table.Functions[Table.Value]
if Case then
Case()
elseif Table.DefaultFunction then
Table.DefaultFunction()
end
end
return Table
end
示例用法:
switch(Player:GetName())
.case("Kate", function() print("This player's name rhymes with Fate")end)
.case("Tod", function() print("This player's name rhymes with Cod") end)
.default(function() print("This player's name is not Kate or Tod") end)
.process()