Hey! I have an if loop with a decent amount of conditions that I don’t want in the same line.
if table.find(keybinds, input.KeyCode) or input.UserInputType == Enum.UserInputType.Touch or input.UserInputType == Enum.UserInputType.MouseButton1 then
-- code
end
I tried spreading it across multiple lines, and now it’s more readable, but it looks a little… weird.
if
table.find(keybinds, input.KeyCode) or
input.UserInputType == Enum.UserInputType.Touch or
input.UserInputType == Enum.UserInputType.MouseButton1
then
-- code
end
I’m fairly sure that this second example included in your post is the more recommended way of formatting it since it improves readability (only 1 condition per line) and you don’t need to scroll to the right in the Script Editor to see everything that was written.
Only adjustment I’d make would be to move any operators (or, and, etc.) to the beginning of the next line rather than at the end of each one, as this will make it easier from first glance to know if only one condition needs to be true versus situations where all need to be true:
Example Revision:
if
table.find(keybinds, input.KeyCode)
or input.UserInputType == Enum.UserInputType.Touch
or input.UserInputType == Enum.UserInputType.MouseButton1
then
-- code
end
Yeah, it took me some time to get used to it since it made it look like it wasn’t aligned properly, but it will definitely help save time reading through code in the long run, especially with much longer scripts.
Oh, and also one slight correction for future reference; these are called if statements / conditional statements and not if loops, as loops tend to refer to things like this:
for count = 0, 10, 1 do
print(count)
end
-- Or
for index, object in workspace:GetDescendants() do
print(object.Name)
end
So what you were referring to in your original post would be something closer to “an if statement with multiple conditions”.
I actually have another recommendation for this refactoring:
local function isInputValid(input)
local acceptedInputTypes = {
Enum.UserInputType.Touch,
Enum.UserInputType.MouseButton1
}
return table.find(keybinds, input.KeyCode) or table.find(input.UserInputType, acceptedInputTypes)
end
if isInputValid(input) then
-- code execution here
end
For context, I was once told that if the condition is becoming excessively long, try to squash it in a function like that and give it a name.