Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

why does this function not print anything?

i have this modulescript and localscript, and when the modulescript function is running it should print running, but it doesnt say anything, here is my code:

--localscript code:

local myModule = require(workspace.KeyHandler)

game:GetService("UserInputService").InputBegan:connect(myModule.onKeyPress())
--modulescript code:
local module = {}

function module.onKeyPress(inputObject, gameProcessedEvent)
	print("running...")
	if inputObject.KeyCode == Enum.KeyCode.Space then
		print("Spacebar was pressed")
		if(_G.wt1 == true) then
			_G.wt1 = false
			_G.WelcomeText2()
		elseif(_G.wt3 == true) then
			_G.wt3 = false
			_G.WelcomeText4()		
		end		
	end
end

return module

if anyone could figure this out I would be grateful, thanks in advance!

2 answers

✓ Accepted answer

The function in the module script has 2 parameters, inputObject and gameProcessedEvent. The function needs those 2 parameters in order to run properly. In the main script, you just have the function be called whenever the inputbegan event is fired, but you're not passing any arguments to the onKeyPress function. This can be fixed by simply getting the arguments passed to the inputBegan function, and then passing those to the onKeyPress function, like so:

--localscript code:

local myModule = require(workspace.KeyHandler)

game:GetService("UserInputService").InputBegan:connect(function(inputObject, gameProcessedEvent)
	myModule.onKeyPress(inputObject, gameProcessedEvent)
end)

Or you can just connect the function directly to the event like bluetaslem's answer, like so:

--localscript code:

local myModule = require(workspace.KeyHandler)

game:GetService("UserInputService").InputBegan:connect(myModule.onKeyPress)

Both methods work properly

Hope this helped!

1 comment

0

It worked, thank you.

In this line,

game:GetService("UserInputService").InputBegan:connect(myModule.onKeyPress())

You call the function myModule.onKeyPress with no arguments (inputObject and gameProcessedEvent on line 4 of the module will both be nil).

Since you called it, it should immediately print "running...", then error, because inputObject is nil.


You are supposed to give :connect a function. onKeyPress is a function. onKeyPress() is what it returns which is nothing -- not a function.

You just need to drop the ():

game:GetService("UserInputService").InputBegan:connect(myModule.onKeyPress)

Using _G is really not a good idea for keeping your code clean or understandable.

This discussion is preserved as it was. New answers, comments, and votes are closed.