"while true do" isn't looping

I’m currently working on a ModuleScript that runs a game loop for some game I’m working on. The function is supposed to start the game loop and I want to loop a section of code for every time the player presses an input. It works once but then stops for some reason. Am I doing the loop wrong?

Here is the script so far:

local gameLoop = {}

local userInputService = game:GetService("UserInputService")

local inputModule = require(script.Parent.Input)

function gameLoop.run()
	local newInput = inputModule.new()
	local regInput = newInput.regInput
	--This "while true do" is what I want to cycle for every input.
	while true do
		local inputBegan = userInputService.InputBegan
		
		local input, gameProcessed = inputBegan:Wait()
		
		if gameProcessed then 
			continue
		end
		
		if input.UserInputType == Enum.UserInputType.Keyboard then
			break
		end
		
		inputBegan:Connect(function(key)
			regInput(key)
		end)
	end
end

return gameLoop

Thanks!

1 Like

try wrapping it in a task.spawn like this:

task.spawn(function()
    --while loop here
end)
1 Like

Put some type of print statement in there and some sort of ‘wait’ to make sure its actually even looping once

I did, I figured out the looping part by simply putting the part that waits into a separate function.

local gameLoop = {}

local userInputService = game:GetService("UserInputService")

local inputModule = require(script.Parent.Input)

function gameLoop.run()
	local newInput = inputModule.new()
	local regInput = newInput.regInput
	
	while true do
		local inputBegan = userInputService.InputBegan
		
		waitI(inputBegan)
		
		inputBegan:Connect(function(key)
			print("a")
			regInput(key)
		end)
	end
end

function waitI(source)
	while true do
		local input, gameProcessed = source:Wait()
		if gameProcessed then 
			continue
		end
		if input.UserInputType == Enum.UserInputType.Keyboard then
			break
		end
	end
end

return gameLoop

But now I am having an issue that I am trying to figure out where I need to press an input once before it prints anything. So any help surrounding that would be great.

Are you calling the function from the local side? UIS can only be called from the local side.

Yes I am, I fortunately don’t really have to worry about much surrounding that considering this is a completely client sided game. And I did get this problem figured out, but any ideas you have regarding my previous post on here would help me greatly.

Nevermind, I got this all figured out. Thank you all for your time.

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