Using tables instead of if-else statements

Hello!

I have an OnUpdate() loop, (which pretty obviously runs every frame), which has some very dirty code in it.
Here’s what i’m trying to get rid of/optimize;

                        if not aiming then --update when changed player state
				springdivider = 1.5
				currentmovement = defaultmovement --update bobbing			
			else
				springdivider = 25
				currentmovement  = aimingmovement
			end
			if not aiming and crouching then
				springdivider = 5
				currentmovement = crouchingmovement	
			end
			if running then
				currentmovement = runningmovement
			end

currentmovement is a variable that leads to a table housing the needed calculation variables;

local crouchingmovement = {
	multiplierx = 3,
	multipliery = 3,
	dividerx = 0.3,
	dividery = 0.2
}

while springdivider just changes spring movement.

If you have any better ways to replace this mess, please feel free to share.

2 Likes

Use ternary expression.

springdiver = aiming and 25 or (crouching and 5 or 15);
currentmovement = (running and runningmovement) or (aiming and defaultmovement) or (crouching and crouchingmovement or aimingmovement);

With just those 2 statements you’re basically doing the same thing as your if statements.

3 Likes

Conditional statements aren’t “dirty code”. They’re computationally cheap, and make for easily readable code. Ternary expressions can be useful, but I think this really isn’t the best place for them.

Remember - more lines doesn’t mean worse code!

1 Like

I don’t think your original code is bad, but it might not be necessary. For instance, where are you setting aiming or crouching? Couldn’t you just change the values of springdivider and currentmovement there instead? Are you using events to trigger those values to change? If so, you could shift your code to be more event-based, which is typically a lot more efficient.

Regardless, your current code won’t have any performance issues. In fact, using a table would relatively hurt performance due to making table index lookups (but still wouldn’t be noticeable at this scale).

3 Likes

I’ve only recently realized or and “expressions” work outside of if statements. thanks.