Attempt to index nil with self

I’m fairly new to OOP and I was making a module for some game, but the module seems to give me an error.

Server:

local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")

local LeMap = require(ServerScriptService:WaitForChild("LeMap"))

local Segments = workspace:WaitForChild("Segments")
local InGameSegments = workspace:WaitForChild("InGameSegments")

Players.PlayerAdded:Connect(function(Player)
	local Map = LeMap.new(Player, Segments)
	print(Map) --> '{["Player"] = H3kken, ["SegmentsFolder"] = Segments}'
	
	Map.NewSegment()
	
	Player.CharacterAdded:Connect(function(Character)
		print("CharacterAdded")
	end)
end)

Module:

local LeMap = {}

LeMap.__index = LeMap

function LeMap.new(Player, SegmentsFolder)
	print(Player, SegmentsFolder) --> 'H3kken Segments'
	local NewMap = {}
	setmetatable(NewMap, LeMap)
	
	NewMap.Player = Player
	NewMap.SegmentsFolder = SegmentsFolder
	
	return NewMap
end

local function PickSegment(self)
	local SegmentTypes = self.SegmentsFolder:GetChildren()
	local ChosenSegmentType = SegmentTypes[math.random(1, #SegmentTypes)]
	
	local Segments = ChosenSegmentType:GetChildren()
	local ChosenSegment = Segments[math.random(1, #Segments)]
	
	return ChosenSegment
end

function LeMap:NewSegment(Root)
	print(self) --> 'nil'
	local Player = self.Player --> 'ServerScriptService.LeMap:30: attempt to index nil with "Player"'
	
	local Segment = PickSegment(self)
	print(Segment) --> Nothing because of error above.
end

return LeMap

I’ve put the errors as a comment on each line.
Can anyone help?

self doesn’t get passed unless you use “:”
change it to:

Map:NewSegment()
2 Likes

Ah, I see now. It’s these small errors you can look at for so long and not notice them. Thanks for the help!

1 Like