Is this a valid way for sending data?

I’ve been trying to find better/cleaner options to write my code and I just found out about a way for sending data but I’m not sure how efficient it is. At the moment it seems like it’ll work well, but yeah I’m not too knowledgable with metatables so perhaps this is a horrible idea in the long run. (to maintian and for performance)

-- Server
function Player.new(player, userId)
	local self = {}
	
	--TODO: Probably have some kind of initial data to send when we create a new player
	
	local player = player
	local userId = userId
	local hero = nil -- probably want to have our own version of hero to access so we dont accidentally send data to the client 
	local replicatedData = {}  -- anything changed in here will be sent to the client

	local mt = {
		__newindex = function(table, key, value)
			remotes.SendData:FireClient(player, {key, value})
		end,
	}

	function self.setHero(heroName)
		hero = require(sharedModules.Heroes[heroName]).new()
		replicatedData.hero = sharedModules.Heroes[heroName] -- can't send the table so instead just send the path to the module to make requiring it easy
	end

	setmetatable(replicatedData, mt)

	return self
end
-- Client
function Client.new()
	local self = {}
	
	local hero = nil
	
	self.player = Player.new(self)
	self.input = Input.new(self)

	local function onDataReceived(data)
		local key = data[1]
		local value = data[2]

		if key == "hero" then
			hero = require(value).new()
			hero.onSelected() -- runs setup code (animations, cosmetics, etc)
		end
	end
	
	function self.getHero()
		return hero
	end
	
	remotes.SendData.OnClientEvent:Connect(onDataReceived)

	return self
end
1 Like