Returning a Value from a Module Script

I’m attempting to pass a value from a module script into a script following the general outline Roblox provided in their example for using module scripts. However, when I print out the values in the two scripts, the module script’s value has something, but the script’s value stays nil. I haven’t found any errors in my own code that deviate from the logic of the example, but I could be wrong. As such, I’d like some external feedback. Are there any errors that stand out from my scripts? Here’s the module script:

-- I transcluded all the variables and functions that aren't involved in returning a value

local raycast = nil

local function createRaycast(parameters: RaycastParams)
	local ray = BindableFunction:Invoke()
	raycast = workspace:Raycast(ray.Origin, ray.Direction * 25, parameters)
end

return function(tool: string)
	
	RemoteEvent.OnServerEvent:Connect(function(player: Player) 
		
		if AnotherModule.anotherModulesFunction("TargetPart") then
			local raycastParams = RaycastParams.new()
			raycastParams.CollisionGroup = "TransformToolHitbox"

			createRaycast(raycastParams)
			
			return raycast
		end
	end)
end

And here’s the script that’s supposed to receive it:

-- This is also very transcluded
local defaultBehavior = require(TheModuleScript)
local raycast = defaultBehavior("Move")

I’m more than willing to give the full script; I just figured it’d be easier to see the related parts than to search through all of it.

I assume raycast is nil?

If so, can you please better explain what you were attempting to do. Otherwise, please clarify which values are nil.

Yes, raycast in the second script stays nil. However, raycast in the first script changes whenever I hit something that’s part of the collision group dictated by the raycast params, as expected. I figured that returning raycast from the first script would allow me to bring it to the second script, but that doesn’t seem to be the case.

As for what I’m trying to do, I’m attempting to make a module script that I’m planning to reuse for other scripts. I just need the variable in the module script in all of the other scripts as well.

The solution was to separate the return line from RemoteEvent. I did this by putting it in another function and deciding to just deal with the extra line of code I’ll be writing in the other scripts.

For those interested, I think the problem has something to do with the fact that I’m confusing Roblox Studio when I told it to return something upon firing RemoteEvent. Maybe it’s trying to return something to whatever fired RemoteEvent, but since RemoteEvent is a remote event, it can’t actually pass it back. Not that I set the script that fires RemoteEvent up to take something anyway. Whether or not that’s truly the reasoning behind it will be beyond me. Feel free to provide your answers before this topic closes.

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