Return the final value in an asynchronous function (coroutine)

Hello everyone, today I was wondering something. I’d like my code to return the final value when my inputState is set to End. However, I tried using global values and had no success…

local function CountSecondPress(limite: number?)
	local s = 0
	while true do
		local start = os.clock()
		if limite and s > limite then
			s = 0
		end
		task.wait(1 - (os.clock() - start))
		s += 1
	end
	return s
end

local count

local function onPass(actionName: string, inputState: Enum.UserInputState)
	if actionName ~= Enums.BindAction.Pass then return end
	if ballEnum ~= Enums.Ball.HasBall then return end
	if isCross then return end
	
	if inputState == Enum.UserInputState.Begin then
		if isPass then return end
		isPass = true
		count = coroutine.create(CountSecondPress)
		coroutine.resume(count, 5)
	else
		coroutine.close(count)
	end
end
1 Like

anglais

1 Like

OH YES SORRYYY i forgot x)))) sorryyy

2 Likes

a bit confused but in

local function CountSecondPress(limite: number?)
	local s = 0
	while true do
		local start = os.clock()
		if limite and s > limite then
			s = 0
		end
		task.wait(1 - (os.clock() - start))
		s += 1
	end
	return s
end

return s wont ever run because the loop doesnt end, ever

your best bet is to make a variable, and make the function change that variable directly so you dont have to return anything

OR instead of while true do, you can make a variable that you turn into false, itd look something like this

local run = true
local function CountSecondPress(limite: number?)
	local s = 0
	while run do
		local start = os.clock()
		if limite and s > limite then
			s = 0
		end
		task.wait(1 - (os.clock() - start))
		s += 1
	end
	return s
end

-- making run = false will cause it to return
run = false
1 Like