Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

why does this function not print anything?

Asked by 8 years ago

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

Log in to vote
0
Answered by 8 years ago

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!

0
It worked, thank you. UltraTechX 10 — 8y
Ad
Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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.

Answer this question