Why is the value in the table not updating?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want the data in the table to update and mirror the player’s leaderstat time value.
    Also any improvements are appreciated! : D
-        local data = {

	
	
}


local sortingdata = coroutine.wrap(function(plr)
	table.insert(data,{plr.Name,plr:WaitForChild("leaderstats").TimePlayed.Value})
	while task.wait() do
		
		for rank, playervalues in pairs(data) do	
			
			
			print(data[rank])
			
			for int,value in pairs(data[rank]) do
				if int == 2 then
					
					
					value = plr:WaitForChild("leaderstats").TimePlayed.Value
				
					print(value) -- The value updates here correctly
				end
	     
			end
		
							
		
		
		end
		print(data) -- when data is printed the value has not updated
		task.wait(1)	
	end
			
					
end)
sorting data(plr) -- plr is from a player added event.

In your code, you are not updating the table value with the new value of plr:WaitForChild("leaderstats").TimePlayed.Value. Instead, you are only printing it out. To update the table value, you can simply assign the new value to the appropriate index in the table. Here’s the modified code:

local data = {}

local function updateData(plr)
	table.insert(data, {plr.Name, plr:WaitForChild("leaderstats").TimePlayed.Value})
	
	while true do
		for rank, playervalues in pairs(data) do
			if playervalues[1] == plr.Name then -- check if the player is in the table
				playervalues[2] = plr:WaitForChild("leaderstats").TimePlayed.Value -- update the value
				print(playervalues[2]) -- print the updated value
			end
		end
		
		print(data) -- print the updated table
		task.wait(1)
	end
end

updateData(player) -- call this function when a new player joins the game

Note that I replaced the coroutine.wrap with a regular function, as there’s no need for a coroutine in this case. Also, instead of looping through the entire table each time, you can simply check if the player is in the table and update their value.

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