I’m making a movement class and it seems to be using a lot of if statements. It looks fine but I’m wondering if anyone here can possibly find a way to optimize it more. If you’re up for a challenge.
(UPDATED CODE)
function Movement.Enable(self: ClassType): ()
-- mobile
self.connections:Connect(UserInputService.TouchSwipe, function(swipeDirection: Enum.SwipeDirection, numberOfTouches: number, gameProcessedEvent: boolean)
if gameProcessedEvent then return end
if swipeDirection == Enum.SwipeDirection.Up then
self:Up()
end
if swipeDirection == Enum.SwipeDirection.Down then
self:Down()
end
if swipeDirection == Enum.SwipeDirection.Left then
self:Left()
end
if swipeDirection == Enum.SwipeDirection.Right then
self:Right()
end
end)
-- pc
self.connections:Connect(UserInputService.InputBegan, function(input: InputObject, gameProcessedEvent: boolean)
if gameProcessedEvent then return end
if table.find(Keys.Up, input.KeyCode) then
print("Up")
end
if table.find(Keys.Down, input.KeyCode) then
print("Down")
end
if table.find(Keys.Left, input.KeyCode) then
print("Left")
end
if table.find(Keys.Right, input.KeyCode) then
print("Right")
end
end)
end
First, I would ask why do you need to use a class. Are there going to be multiple movement managers? Why can’t you just store everything in a record table and run functions on it?
Second, instead of storing the keycodes in an array, store them in a dictionary so that you don’t have to do a linear search.
local Keys = {
Up = {
[Enum.KeyCode.Space] = true,
[Enum.KeyCode.Up] = true
}
}
if Keys.Up[Input.KeyCode] then
print("Up")
end
The if-statements should be fine. You could also use a dictionary for them, but it’d probably be slower.
What is a record table? I got my self into a habit of making movement into a class because I always thought it was better, but I don’t know why I thought it was better.
Technically a ‘record table’ is just a dictionary with implicit string keys. The Luau checker just distinguishes them.
local Movement = {
State = "Up"
Connections = {}
}
local function Connect(Signal: RBXScriptSignal, Callback: (...any) -> ())
table.insert(
Movement.Connections,
Signal:Connect(Callback)
)
end
Connect(UserInputService.TouchSwip, print)
Don’t take this as ‘better’, though. Some situations could benefit from classes in your case.