moosee
(moosee)
May 8, 2021, 6:27pm
1
Hello!
I’ve recently come across an issue that requires a vast amount of checks, something that a C style switch statement would be perfect for, but as it turns out Lua lacks that functionality. In terms of roblox specific Lua, are there any ways for me to handle big blocks of if statements in a much more efficient manner?
Unfortunately it doesn’t really exist. I guess you could make your own implementation of it though:
local function switch(value)
if value == "blah" then
return something
elseif value == 45 then
return somethingElse
end
end
There’s no clear shot though. You could also use a ternary operation if that’s more helpful for your use case:
local x = (not x and 5) or 10
1 Like
heII_ish
(heII_ish)
May 8, 2021, 6:39pm
3
You could use dictionaries to directly look up the case
Something like:
local cases = {
[1] = function()
return print'case 1'
end,
[2] = function()
return print'case 2'
end,
['hello world'] = function()
return print'case hello world'
end,
['default'] = function()
return print'default case'
end,
}
local function handleStuff(case)
local f = cases[case] or cases['default']
return f()
end
handleStuff'hello world'
handleStuff(1)
handleStuff(3)
> case hello world
> case 1
> default case
5 Likes