Is there an equivalent in Lua to Javascript switch() {case n:} ?

is there an equivalent in Lua to this javascript?

[javascript]

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

[/javascript] [import]uid: 21962 topic_id: 6328 reply_id: 306328[/import]

Nope, you have to use if-else-elseif statements. See this for further explanation: http://lua-users.org/wiki/SwitchStatement [import]uid: 8782 topic_id: 6328 reply_id: 21855[/import]

I use the one labeled “Caseof Method” from that page and it works perfectly in Lua, and the code looks rather clean.

Caseof Method:
[lua]function switch©
local swtbl = {
casevar = c,
caseof = function (self, code)
local f
if (self.casevar) then
f = code[self.casevar] or code.default
else
f = code.missing or code.default
end
if f then
if type(f)==“function” then
return f(self.casevar,self)
else
error(“case “…tostring(self.casevar)…” not a function”)
end
end
end
}
return swtbl
end[/lua]

My updated “buttonHandler” function with the new “switch” function:
[lua]buttonHandler = function ( event )
if event.phase == “release” then
switch ( event.id ) : caseof {
[“play”] =
function() – must put “function()” and “end,” to separate
director:changeScene( “levelselect”, “fade” )
end,
[“instr”] =
function()
director:changeScene( “instructions”, “fade” )
end,
[“cred”] =
function()
director:changeScene( “credits”, “fade” )
end,
default = – “default” and “missing” must be added
function()
print( “Button is undefined (default)!” )
end,
missing =
function()
print( “Button is undefined (missing)!” )
end,
}
end
end[/lua] [import]uid: 6084 topic_id: 6328 reply_id: 21968[/import]

BeyondtheTech,

Thanks for sharing. I was looking a for a switch :smiley: [import]uid: 8045 topic_id: 6328 reply_id: 22084[/import]

it also says most of them trash the garbage collector because of function closures. check it’s not affecting your memory badly [import]uid: 6645 topic_id: 6328 reply_id: 22100[/import]