Is this fully functional regenerating fuel code bad practice?

The following working code is used for a jetpack fuel system. The regenerateBoost function is called via a coroutine, so that it works on a separate thread, and thus doesn’t block the flow of other scripts. While the player is not using the jetpack AND the player’s fuel is not at full value, the game will continuously increase the player’s fuel through a while loop. This is placed inside of yet another while loop, which is used to ensure that even if fuel isn’t being incremented, the game is still actively “listening” in the event the fuel drops again. If I didn’t do this then the game would just exit the regenerateBoost function right as the game starts and never return to the inner while loop to regenerate the fuel, as the coroutine is only called once upon player start.

I know using wait() in a condition is bad practice, so I put wait() in the body of the loops instead. But am I still committing some Scripting Sins™?

local function regenerateBoost(player, boostRemaining, isUsingBoost)
	
	while true do
		
		if boostRemaining.Value <= 0 then
			boostRemaining.Value = 0
		end
	
		while boostRemaining.Value < boostStartValue and isUsingBoost.Value == false do
			boostRemaining.Value += 1
			wait(0.09)
		end
		
		wait(0.03)
		
	end

end

If you can update the fuel in the main tool’s loop it’s thought of as better. You can do whatever you like or whatever works. It’s not like there’s going to be 200 of these in a single place.

My preferred style is something like a single function that takes a time delta argument and calculates the boost based on that and any inputs, e.g.

local BoostRegenRate = 11.1 -- how fast to regenerate boost

function RegenerateBoost(dt)
    boostRemaining.Value = math.min(math.max(0,boostRemaining.Value) + BoostRegenRate * dt,boostStartValue)
end

I prefer this method because it works with whatever interval you give it, and you can change the value directly instead of messing with the wait period or the amount to regenerate each tick.

1 Like