How do I pass a model as an argument to a module function?

Hi, I’m new to the forum how’s it goin!
I’m trying to start writing reusable libraries for my game, and I’m still getting to grips with modules.

How do I pass a reference to a model / NPC to a module? When I pass in script.Parent to the below code it gets converted to a table reference:

function NPC.getClosestPlayerTo(npc)
	print(npc)
	local closestPlayer
	local lastDist
	for _, player in pairs(game.Players:GetPlayers()) do
		local dist = player:DistanceFromCharacter( npc.HumanoidRootPart.Position )
		if lastDist == nil or dist < lastDist then
			closestPlayer = player
		end
		lastDist = dist
	end
	-- print(closestPlayer)
	return closestPlayer
end

I can rewrite it to take position co-ordinates of course, but I’m curious how I would do it referencing a model. Cheers!

I think you’re misunderstanding what this table is referring to - It’s actually the module itself. Defining functions this way function module.f(npc), you will actually have to move the parameters which you expect for your function one place to the right e.g. function module.f(module, npc), as the first parameter is ultimately the module itself.

To not have the first parameter being occupied by a reference to the module itself, you will just have to change the . to a : like function moduke:f(npc).

Also, welcome to the devforum! :hugs:

1 Like

That works, thanks!
So that reference gets passed automatically with the dot notation? There I was thinking that it did the opposite - that '.' skipped the self reference, and ':' included self implicitly.
But I guess what that implies is that self expects to be passed either way, but the colon is a shorthand way?

I’ll need to read into it more.