Attempt to call a nil value

I have an issue similar to an old post, ServerScriptService.GameScript:4: attempt to call a nil value - Server - GameScript:4 I have tried following the instructions given by the solution but yet I still get the error.

Module

local PlayerStats = {}
PlayerStats.__index = PlayerStats

function PlayerStats.new()
	local self = setmetatable({}, PlayerStats)
	print("test")
end

return PlayerStats

Server

local PlayerStats = require(game:GetService("ReplicatedStorage").Modules.ModuleScript.leaderstats)

game.Players.PlayerAdded:Connect(function(Player)
	local leaderstats = PlayerStats.new()
end)

Perhaps .new() is a reserved function?
Make sure there are no other scripts with the same name first; that’s sometimes easy to miss.
I don’t know what “__index” is supposed to do; why the two underscores? is that the name or supposed to do something else?

I’m trying to follow a OOP structure for this script.

I’m pretty sure functions don’t get passed to the server.

What do you mean by “don’t get passed”, I have used functions in modules before and they worked perfectly fine, yet this time it decided to break when trying OOP.

Oh wait nevermind, I mixed up the code with another I was reading, sorry! I thought you’re code was the one firing RemoteEvents :sweat_smile:.


function PlayerStats.new()
	local self = setmetatable({}, PlayerStats)
	print("test")
end

U need to return self:

function PlayerStats.new()
	local self = setmetatable({}, PlayerStats)
	print("test")

	return self
end

I still get the same error, would it possibly be the way I required the module?

Are you sure it doesn’t work? I just replicated your code and it worked after adding the return statement.

Extra

image

local PlayerStats = require(game:GetService("ReplicatedStorage").ModuleScript) -- changed to match where I put mine.

game.Players.PlayerAdded:Connect(function(Player)
    local leaderstats = PlayerStats.new()
end)
local PlayerStats = {}
PlayerStats.__index = PlayerStats

function PlayerStats.new()
    local self = setmetatable({}, PlayerStats)
    print("test")
    return self
end

return PlayerStats

The error is saying that whatever you’re requiring doesn’t have a key named new. I’d print PlayerStats after requiring it just to double check that it’s what you expect.

1 Like

Thank you found out that it prints an empty table, how would i go about fixing this?
edit (thanks to the suggestion i have found a solution)

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