Why is it printing nil?

I have a server and a module script
In the module script
the function "NPC:Select is assinging a table to selectedBy[tag] so that table[tag] is not nil and then i added the npc into that table.
then in the server script i insert 2 ally npcs from that class and then i fire the select function so these are inserted inside of SelectedBy[“Ally”] then when i call the move function with the same tag of “Ally” it somehow prints nil, why is this happening?
Module script:

local NPC = {}
NPC.__index = NPC
local selectedBy = {}--the table
function NPC:New(tag, Name, Pos)
	local self = setmetatable({}, NPC)
	self.Character = serverStorage.Dummy:Clone()
	self.Humanoid = self.Character.Humanoid
	self.TargetLocation = nil
	self.Selected = false

	--Initiation
	self.Character.PrimaryPart.Position = Pos + Vector3.new(0,3,0)
	self.Character.Parent = workspace
	self.Character.Parent = workspace
	self.Character.CharacterName.TextLabel.Text = Name
	if tag == "Enemy" then
		self.Character.CharacterName.TextLabel.TextColor3 = Color3.new(0.666667, 0, 0)
	end
	
	return self
end
function NPC:Select(NPC, tag)
	if selectedBy[tag] == nil then
		selectedBy[tag] = {}
	end
	table.insert(selectedBy[tag],NPC)
	
end
function NPC:ClearSelection(tag)
	for i in ipairs(selectedBy[tag]) do
		selectedBy[tag][i] = nil
	end
end

function NPC:Move(pos: Vector3, tag)
	
	--self.Humanoid:MoveTo(pos)
	for i,v in ipairs(selectedBy[tag]) do
		print(selectedBy[tag][v]) -- that line is printing nil
		
	end
	
	
end

Server script

local NPC_Control = require(script.NPC)

wait(3)
local controlledNpcs= {}
controlledNpcs[1] = NPC_Control:New("Ally", "soldier", Vector3.new(0,0,0))
controlledNpcs[2] = NPC_Control:New("Enemy", "Counter", Vector3.new(20,0,0))
controlledNpcs[3] = NPC_Control:New("Ally", "Pawn", Vector3.new(00,0,0))

wait(2)
NPC_Control:Select(controlledNpcs[1], "Ally")
NPC_Control:Select(controlledNpcs[3], "Ally")
wait(2)
NPC_Control:Move(Vector3.new(-20,0,0), "Ally")

Because your already looping through the table, you would need to do something like this,

for i,v in ipairs(selectedBy[tag]) do
		print(v)	
	end

or

for i,v in ipairs(selectedBy[tag]) do
		print(selectedBy[v])
		
	end

test them both out, I think only one of them might work.

1 Like