Module Funtcion Return Value Nil(null)

  1. What to do? A: I’m trying to call a function in a module from a script and get the return value.
  2. Problem A: The return value called and received from the module script is nil.
  3. Trial A: I tried removing the require code above the return code. And I printed the variable using print.
  4. The solution I think A: Create and execute a separate Thread in the require statement.

If you are very smart or know a solution to this problem, please leave a comment.

Module Script :

PCI1Slot.Touched:Connect(function(PCIotherPart:BasePart)
            if PCIotherPart.Parent:IsA("Model") then
                local PCIDevice = PCIotherPart.Parent
                if PCIDevice:FindFirstChild("GraphicChip") then
                    require(PCIDevice.GraphicChip.GraphicChip).Power(PCI_ControllerVar)
                    print(PCIDevice)
                    return PCIDevice
                else
                    require(PCIDevice.PCIModule.PCIModule).Set_PCI_Controller(PCI_ControllerVar)
                    return PCIDevice
                end
            end
        end)

Function Script :

function ReadyPOST()
    GraphicCard = require(PCI_Controller.PCI_Controller).GetPCIDevice(1)
    print(GraphicCard)
end

Addition: I saw that the calling script first says nil and then prints the PCIDevice.

1 Like

I’m a bit confused but I’ll try my best. From what it looks like in the module script you’re making an event and then returning the PCIDevice, which I assume is the value you want to return. Firstly this won’t return the given value because its returning in a different function.
For example, module script:

local module = {}
workspace.ChildAdded:Connct(function()
  return 'it wont return this'
end)
return 'it will return this'

Script

local module = require(pathtomodule)
print(module) -- 'it will return this'

This is because :Connect() creates a thread for when that event is fired and isn’t in the modules’ scope.

Instead of creating a connection you can just wait or search for a device.
module script:

local PCIDevice = {}

-- searching
for _, v in PCI1Slot:GetTouchingParts() do -- loop thru touching parts
  if v.Name == 'GraphicChip' then -- if find GraphicChip part
    -- do stuff
    return PCIDevice
  end
end
-- return also haults a script so if it gets to here it means GraphicChip hasn't been found
return PCIDevice

Or you can also wait for it after searching by using Touched:Wait() which halts the script until the events been fired

local PCIotherPart = PCI1Slot.Touched:Wait()
if PCIotherPart.name == 'GraphicsChip' then
  -- do stuff
end
-- if not you can :Wait() again for the next one.
2 Likes

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