Variable help!

I need a way for a client sided script to access a variable on the server. I need the players’ HUD to display a value found inside a file in the server’s data folder. How do I go about doing this?

have the server use SendLua

   player:SendLua("MyVariable = 9001")

No no no no no.

No? Explain.

SendLua is bad.


There are some situations where you can use it well, but don’t use it here.

What is a good method then?

There’s two primary methods of sending server data to clients: usermessages and datastream.

I would read up on the wiki to learn more about those.

Datastream all the way.

Datastream is completely unnecessary. Use GetGlobalString.

Can someone help me I’m extremely confused. I have a number saved in files in the server’s data folder. I need that number sent to the clients for use on their HUD.

Server side…

local function Initialize( )

// read the file
local contents = file.Read( "path/to/file.txt" );

// and set it as a global number
SetGlobalFloat( "YourGlobalNumber", tonumber( contents ) );

// do it once the server initializes
hook.Add( “Initialize”, “ReadYourFile”, Initialize );

Client side:

local function HUDPaint( )

// get the global number
local number = GetGlobalFloat( "YourGlobalNumber" );

hook.Add( “HUDPaint”, “PaintYourNumber”, HUDPaint );

While Nevec’s method does indeed work, if you want to keep the data individual to the client OR send a lot of data I would use datastream.

If you want the data to be available only on a specific client, use plain usermessages. Use datastream only if you have a lot of data.

Thank you I will try. It’s for a money system for all the player that join so this should be good.

They are buggy and can be unreliable, I would suggest using usermessages. GetGlobalString is just a wrapper for usermessages.

What is the best way to send the client part of it to all clients and have it run on all clients?

If you’re sending data under 255 bytes then there is absolutely no reason to use datastream.

There’s absolutely no reason to use gmod’s nwvars with strings. They are spammed constantly to the client and cause overflows.

Only use the datastream if you have a really long string or a table to send. Usermessages for anything shorter, and SendLua for anything unexploitable but not worth setting up a usermessage for.

Use a usermessage and send them the variable when it is updated, it is a much better alternative to using networked or global variables. There are about five links above to usermessages, find one and go read up about them and try it out. They are very simple once you know what they do.