Returned Value is nil if it's inside an if statement

Hello! I am writing a sort of ModuleScript for some calculation I need to make and the problem is that n, the returned value, is nil, according to a print statement. I have tried the other way around with if not and then making the recursive loop happen and also setting the return at the bottom of the function, since I thought it will not stop the function but return seems to stop the function already. However it did give me a value, n (or 1) Is there any way I can get the returned value somehow without stopping the recursive function until the calculation is right. Any help appreciated!

local n = 0
function CalculationService:CalculateFactorNinExponentialIncrease(FactorAsDecimal: number, StartValue: number, EndValue: number)
	task.wait() -- if recursive
	if StartValue > EndValue then error("StartValue must be smaller than EndValue") end
	local Factor = 1 + FactorAsDecimal
	local PreviousNumber = StartValue * Factor
	n += 1
	local CurrentNumber = StartValue * Factor^2
	if (PreviousNumber < EndValue) and (CurrentNumber > EndValue) then
		task.spawn(function()
			task.wait(.1)
			n = 0
		end)
		return n
	else
		print(PreviousNumber, CurrentNumber)
		CalculationService:CalculateFactorNinExponentialIncrease(FactorAsDecimal, PreviousNumber, EndValue)
	end	
end

Hello, Here is a potential fix. Tell me if anything is wrong/broken.

function CalculationService:CalculateFactorNinExponentialIncrease(FactorAsDecimal: number, StartValue: number, EndValue: number)
    local n = 0
    if StartValue >= EndValue then
        error("StartValue must be smaller than EndValue")
    end

    local Factor = 1 + FactorAsDecimal
    local PreviousNumber = StartValue

    while PreviousNumber < EndValue do
        n = n + 1
        local CurrentNumber = PreviousNumber * Factor
        if CurrentNumber > EndValue then
            break
        end

        print(PreviousNumber, CurrentNumber)
        PreviousNumber = CurrentNumber
    end

    return n
end
1 Like

Woa it really helped! Thanks, I have been stuck here for like an hour to fix that lol

You’re welcome, if you need any more help message me. :+1:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.