Is there any meaningful difference between using a new if statement or adding an elseif?

Greetings,

I am just wondering is there any difference?

For instance on user input

if key = F

elseif key = G

end

or using

if key = F

end

if key = G

end

Is there a difference? Is there a better way between the two?

Thank you for your time

local x, y = false, true
if x then
    print(1)
elseif y then
    print(2)
end

x = true

if x then
    print(3)
end

if y then
    print(4)
end

The body of the last 2 ifs were executed. But in the if ... elseif block only the elseif block executed. So elseifs are for running alternate logic if the first condition of the if or previous elseifs is falsey

1 Like

I know that much, but if it’s not F key it will skip over it just as it would if it were part of an elseif statement right?
I am wondering about the perticular scenario i’ve posted, where i have a script that runs 5 various key inputs. Should I arrange them in an elseif list or just make an individual if statement for every key

The former. It is more clean and organized. Less ends too. But for your case I would use a table of functions.

local functions = {
    [Enum.KeyCode.F] = function()
        -- code that runs when F key is pressed
    end,

    [Enum.KeyCode.G] = function()
        -- code that runs when G key is pressed
    end,
    
    -- and so on
}
4 Likes

and how would i call these function?

local f = functions[input.KeyCode]

if f then
    f()
end
4 Likes

that seems like a lot of trouble for not much gain, since I don’t actually know which spell is cast i think i’ll just use elseif statements for now. Thanks for the help

1 Like