How to optimize code when theres too many "else if" s

I was wondering if there was a better version of laying this out:

    local number = 7

    if number == 1 then
    elseif number == 2 then

    elseif number == 3 then
    elseif number == 4 then

     ---etc...
     end

in other softwares they use something called switch, but roblox doesnt have that

Unfortunately, Roblox doesn’t have switches. But another way that you could organize code like that is to use a dictionary instead:

local tableOfFunctions = {
[1] = function()
end,
[2] = function()
end,
}

And so on, and call it using tableOfFunctions[index](). Not sure if it’s more efficient, though I would assume so given the fact that it doesn’t need to calculate for each case every time. Hope I helped!

thanks, this is just what I need!

Just to offer some more perspective…

Although ninja’s approach is very useful sometimes, it gets slightly messier when you want to add an “else”; you either have to add an __index metamethod to the tableOfFunctions or call it like (tableOfFunctions[index] or elseFunction)(). Which isn’t necessarily bad, but if you are doing very simple things in each elseif statement, it might be better to leave it how it is.
In other words, there’s no such thing as “too many” elseifs. It’s a balancing act between readability, simplicity, and abstraction.
Another thing you could do is break out the if elseif block into a new function.

function doThing(number)
    if number == 1 then
    elseif number == 2 then
    ...
end

local number = 7
doThing(number)
2 Likes

Nope; if anything it’s less efficient. Creating a brand new function for each possible case will take up more memory.

4 Likes