Returning a table with instances as keys cause strings to be returned

Problem is if you use an instance as the key of a table, and try to return said table to client, the instance can’t be used, and instead a string is returned??

-- Server
local Data = {}

game.Players.PlayerAdded:Connect(function(player)
	Data[player] = {
		["Tags"] = 10,
		["Deaths"] = 2,
		["Streak"] = 10,
	}
end)

game.ReplicatedStorage.Return.OnServerEvent:Connect(function(player)
	game.ReplicatedStorage.Return:FireAllClients(Data)
end)
script.Parent.Activated:Connect(function()
	game.ReplicatedStorage.Return:FireServer()
end)

game.ReplicatedStorage.Return.OnClientEvent:Connect(function(data)
	for player, data in pairs(data) do
		print(player.DisplayName) -- prints nil
	end
end)

Printing type(player) returns a string, even tho I am storing it as an instance on the server.

I don’t want a “workaround”, as I am using these in several locations in my games, and it will take forever to rework.

Repro
Instanced objects bug.rbxl (31.7 KB)

4 Likes

Yeah, it seems like what’s happening is not suppose to happen.
Considering that when you print out the key that is suppose to the be instance of the player it comes out with a extra tag <Instance> PlayerName so I’m guessing something was messed up on the end that processes that tag.

2 Likes

This is intended behavior and is documented here under " Non-String Indices". If you do want this behavior I suggest supporting this feature request.

3 Likes

As noted above, this is the intended behavior, and is also unlikely to change.

Serialization should generally be as done with as simple / flat a format as possible, and remotes working this way pushes people in that direction rather than cramming existing structures that weren’t designed with serialization in mind through a remote.

5 Likes

I wrote something up that can you can chuck in and it’ll just work,. I’ll post it when I get home.

function  module.tableSerialize(myTable)
	local tempTable = {}
	local i =1
	for k,v in pairs(myTable) do
		if type(v)=="table" then
			v=module.tableSerialize(v)
		end
		tempTable[i] = {k,v}
		i+=1
	end
	return tempTable
end


function  module.tableDeserialize(myTable)
	local tempTable = {}
	for _,t in pairs(myTable) do
		if type(t[2]) == "table" then
			t[2] = module.tableDeserialize(t[2])
		end
		tempTable[t[1]] = t[2]
	end
	return tempTable
end