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

how to make a localscript call this function correctly?

i recently created this modulescript:

local module = {}

function module.onKeyPress(inputObject, gameProcessedEvent)
	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

and it is referenced using a localscript that is placed in the players character on startup with this code:

local myModule = require(workspace.KeyHandler)

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

but when this code runs I get:

attempt to call a nil value

so how can I fix this error? Thanks in advance!

2 answers

✓ Accepted answer

Only methods use colons, just connect to the function like what you would do with any other function.

--- Module Script
local module = {}

function module.onKeyPress(inputObject, gameProcessedEvent)
    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


---Local script

local myModule = require(workspace.KeyHandler)

game:GetService("UserInputService").InputBegan:connect(myModule.onKeyPress) -- You connect to the function like this

-- Only methods use colons, if you have a function set as a key in the table then you can just connect to it like in the above.


1 comment

0

thanks, the error no longer comes up, but its not running like expected, ill make a new question for that though

When you make a simple onTouched script...

--Right
function onTouched(hit)
	hit:Destroy()
end

script.Parent.Touched:connect(onTouched)

You do not call the function, you just give its name to the event.

--Wrong
function onTouched(hit)
	hit:Destroy()
end

script.Parent.Touched:connect(onTouched()) --Error here

To apply that to your script:

local myModule = require(workspace.KeyHandler)

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

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