How to send static data without buffer overflows

Here’s a quick and simple way to send data which isn’t updated constantly to the client without having to use usermessages or datastream.

First, fill all the info you want into a text file and save it somewhere on the server’s data/ folder.

Example:

Server:
[lua]
resource.AddSingleFile(“data/mymod/staticdata.txt”)
[/lua]

Client:
[lua]
local staticdata = file.Read(“data/mymod/staticdata.txt”)

local function ClearStaticData( ply )
file.Delete(“data/mymod/staticdata.txt”)
end
hook.Add( “ShutDown”, “ClearStaticData”, ClearStaticData )
[/lua]

You must add the last hook in order to force the client to redownload the file so it stays up to date the next time they join.

Here’s an example of how to send a table:

Server:
[lua]
local mytable = {“bah”,“somuch”,“table”,“aah”}
local str = string.Implode("|",mytable)
file.Write(“data/mymod/staticdata.txt”,str)
resource.AddSingleFile(“data/mymod/staticdata.txt”)
[/lua]

Client:
[lua]
local staticdata = file.Read(“data/mymod/staticdata.txt”)
staticdata = string.Explode("|",staticdata)
PrintTable(staticdata)
local function ClearStaticData( ply )
file.Delete(“data/mymod/staticdata.txt”)
end
hook.Add( “ShutDown”, “ClearStaticData”, ClearStaticData )
[/lua]
Not exactly a complicated thing, but it’s a very useful way to prevent buffer overflows.

And when it is static, why not declare it in a cl_ file?

This assumes that the person using this does not use sv_downloadurl without linking the files to the actual server.

[editline]03:55PM[/editline]

[lua]
local mytable = file.Find(“mygamemode/gamemode/files/”)
[/lua]
You could use it to send a list of files a client needs to include without having to update it constantly.

This is technically what you are doing, actually. You’re declaring the file as a clientside sent file.

What happens when you crash and the file doesn’t get deleted or is half way written and then you go into gmod and join another server who uses the same file (public gamemode/script) and the script loads another server’s data or errors out?

You should always check for consistency, no matter what. This could be as simple as a util.CRC check. In truth, though, I wouldn’t use the same filename for everything or hold any really important info in there.