Skip to content

Instantly share code, notes, and snippets.

@EngineerSmith
Created May 30, 2023 00:08
Show Gist options
  • Select an option

  • Save EngineerSmith/2d25b2a26db62fac8f244103ed650b6f to your computer and use it in GitHub Desktop.

Select an option

Save EngineerSmith/2d25b2a26db62fac8f244103ed650b6f to your computer and use it in GitHub Desktop.
local dict = {
"commonly",
"used",
"strings", -- these strings, are not just values but keys too in a table!
}
-- send dict to client from server, so they are in sync and can decode the messages
local buffer = require("string.buffer)"
local data = buffer.encode(dict) -- send string to client, and do buffer.decode on it, so it can use it same as the server
-- recive dict, or already has dict if the server
local options = {
dict = dict
}
local encoder, decoder = buffer.new(options), buffer.new(options)
local encode = function(val)
return encoder:reset():encode(val):get()
end
local decode = function(val)
return decoder:set(val):decode()
end
-- encode outgoing data, decode incoming data
-- it's a little more complex after that, but that's the basics for how I handle making the actual lua data, I have other systems that handle the direction for where it goes
-- but simply:
-- shared file between client + server
network.addType("chatMessage", "c") -- "c" is appended infront of the message sent
-- server
network.addHandle("chatMessage", function(client, message) -- incoming chatMessage
-- ... validation
network.sendAll("chatMessage", client.username .. ">" .. message) -- sends message to all clients
-- ... logging
end)
-- client
chat.addSink(function(message) -- get messages from chat table when user hits enter
network.send("chatMessage", message) -- encoded within func, send to server
end)
network.addHandle("chatMessage", function(message) -- incoming chatMessage
chat.addMessage(message)
end)
-- so usually ends up looking like
-- <type><data>, e.g. c&Hello world&
-- I also take advantage of enet's channels if I want to send a encoded Lua object, or a bytedata object so I know what kind of data they are without having to append anything
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment