Howdy!
Quick Q: How can I implement a ‘switch’ statement? I can’t see it existing in Lua/Corona.
TIA [import]uid: 10389 topic_id: 3625 reply_id: 303625[/import]
Howdy!
Quick Q: How can I implement a ‘switch’ statement? I can’t see it existing in Lua/Corona.
TIA [import]uid: 10389 topic_id: 3625 reply_id: 303625[/import]
Hi WauloK, there are several methods of implementing it, here is a link to that resource.
http://lua-users.org/wiki/SwitchStatement
cheers,
Jayant C Varma [import]uid: 3826 topic_id: 3625 reply_id: 11395[/import]
i like this one… looks neatest
[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
–
c = 1
switch© : caseof {
[1] = function (x) print(x,“one”) end,
[2] = function (x) print(x,“two”) end,
[3] = 12345, – this is an invalid case stmt
default = function (x) print(x,“default”) end,
missing = function (x) print(x,“missing”) end,
}[/lua]
note you can say
[lua]function whatever()
print(“whatever”)
function
switch© : caseof {
[2] = whatever,[/lua] but if you want to pass parameters you’ll need to do [lua]function whatever(n)
print("whatever: "…n)
end
switch© : caseof {
[2] = function() whatever(“trevor”) end,[/lua]
[import]uid: 6645 topic_id: 3625 reply_id: 11396[/import]