Module doesn't return up to date table?

I have a module that tracks a players progress on a tower, and in the return, I return ‘Heights’ as the table of player heights.

local Heights = {}

local Heartbeat

-- Update all players progress
local function Update()
	for _, player in pairs(Players:GetPlayers()) do
		if player.Character and player.Character:FindFirstChild('HumanoidRootPart') then
			if not Heights[player] then -- Check if player has been added to table
				Heights[player] = 0
			end
			
			-- Calculate players distance
			local Distance = math.floor(player.Character.HumanoidRootPart.Position.Y - Start.Floor.Position.Y - 2)
			--print('Height:', Heights[player], 'Distance', Distance)
			if Heights[player] > Distance then return end
			
			Heights[player] = Distance
		end
	end
end

-- Setup the Heartbeat function
local function Setup()
	-- Update
	Heartbeat = RunService.Heartbeat:Connect(Update)
end

-- Disconnect the Heartbeat function
local function Disconnect()
	Heartbeat:Disconnect()
end

-- Clear Heights table
local function ClearHeights()
	Heights = {}
end

return {
	Setup = Setup,
	Disconnect = Disconnect,
	ClearHeights = ClearHeights,
	Heights = Heights
}

However, whenever I call this, it always returns an old version of the table?

local Progress = require(script.Parent.Parent.Progress)

return function()
	for player, height in pairs(Progress.Heights) do
		print(player, height)
	end
end

So for example,

print(player, height)

May print

NinjoOnline 26

The first time round. But then when I start new round, all the players previous scores and removed from the table and re-inserted as 0 when the round restarts. I’ve done prints inside the main code, and the heights are 100% being reset each round.

if not Heights[player] then -- Check if player has been added to table
	Heights[player] = 0
    print(player, "new height of: ", Heights[player]) -- prints at the start of each round for each player
end

But in the other module, I still get

NinjoOnline 26

Even if my player stays still the whole time (so there score should be 0)

Why is it not taking the most up to date Heights table?

1 Like

Your ClearHeights function Does not clear the table that The module returned This is because when u require a Module for the first time in a enviroment the Module gets ran and the return value is stored so when the next time u require it in the same enviroment u will get the stored value.

When u do Heights = {} you’re just reassigning the variable with a new table. The table that the module returns is still referencing the old Heights table.

How can I have it return the updated table?

You can make everything inside of the Heights table nil using a loop.