How to fix attempt to call a nil value error on module function usage

I’m making a party system for my horror game that previously works but now gives this error:
Players.starrstrux.PlayerScripts.ClientMain:17: attempt to call a nil value - Client - ClientMain:17
14:31:20.326 Stack Begin - Studio
14:31:20.327 Script ‘Players.starrstrux.PlayerScripts.ClientMain’, Line 17 - Studio - ClientMain:17
14:31:20.327 Stack End - Studio

LobbyUIHandler.Initialize(script.LobbyUI) -- The line where I'm getting the error
task.wait(5)

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlayerGui = game.Players.LocalPlayer:WaitForChild("PlayerGui")

local Modules = ReplicatedStorage:WaitForChild("Assets"):WaitForChild("Modules")

--local NotificationManager = require(Modules:WaitForChild("NotificationManager"))
local LobbyUIHandler = require(script:WaitForChild("LobbyUIHandler"))
local RoleShopUIHandler = require(script:WaitForChild("RoleShopUIHandler"))

print("Client Main Script Initialized.")

LobbyUIHandler.Initialize(script.LobbyUI) -- (line 17)
RoleShopUIHandler.Initialize(PlayerGui.LobbyUI.MainFrame.RoleShopSection)

local TeleportService = game:GetService("TeleportService")
local teleportData = TeleportService:GetLocalPlayerTeleportData()

if teleportData and teleportData.partyCode then
	print("Received teleport data:", teleportData)
	if teleportData.isPrivate then
		ReplicatedStorage.Events.RemoteEvents.JoinParty:FireServer(teleportData.partyCode, teleportData.password)
	else
		ReplicatedStorage.Events.RemoteEvents.JoinParty:FireServer(teleportData.partyCode, "")
	end
end

LobbyUIHandler (snippet):

local LobbyUIHandler = {}

function LobbyUIHandler.Initialize(ui)
	print("ran")
	
	LobbyUI = ui -- This is the main ScreenGui for the lobby
	LobbyUI.Parent = LocalPlayer.PlayerGui
	LobbyUI.Enabled = true -- Ensure the ScreenGui is enabled

      -- ... and the rest of the function
end

return LobbyUIHandler

Let me know if more code/snippets are needed. Thank you for your time.

1 Like

Strange error, your code looks fine, can you print the LobbyUIHandler table to see if it’s perhaps getting overwritten somehow?

It’s probably still waiting to require it, and then you try to call Initialize. Test this hypothesis by adding wait(4) before Initialize call

Everything runs serially on one thread, there’s no race condition to be had there.

I figured it out. I had a syntax error in one of my functions but it wasn’t directly showing it to me for some reason. Should’ve gave it a full check lol

This is why, :WaitForChild() is the goat