Skip to content

Instantly share code, notes, and snippets.

@maritaria
Created April 19, 2016 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maritaria/7f9d5da3b1efd2680543b42f03574dd8 to your computer and use it in GitHub Desktop.
Save maritaria/7f9d5da3b1efd2680543b42f03574dd8 to your computer and use it in GitHub Desktop.
NWVars fix
--[[--
Script from some base entity I once made,
usage:
Call InitProperties() from the entity's Init method.
Call ThinkProperties() from the entity's Think method.
This solution is kinda heavy because it uses think to find changes in the variables
--]]--
function ENT:InitProperties()
self.PropertyProxyList = {};
self.PropertyProxyCache = {};
self:NetworkedProperty("Float", "PreferredSize", self.Config.PreferredSize);
end
function ENT:NetworkedProperty(propertyType, propertyName, initialValue)
local rawSetter = self["SetNW" .. propertyType];
local rawGetter = self["GetNW" .. propertyType];
assert(rawSetter and rawGetter, "Invalid property type: " .. propertyType);
self["Set" .. propertyName] = function(self, value)
assert(SERVER, "Cannot change networked property client-side");
rawSetter(self, propertyName, value);
end
self["Get" .. propertyName] = function(self)
return rawGetter(self, propertyName);
end
local callback = self["On" .. propertyName .. "Changed"];
if callback then
self:SetNWVarProxy(propertyName, callback);
table.insert(self.PropertyProxyList, propertyName);
end
if SERVER then
rawSetter(self, propertyName, initialValue);
end
end
function ENT:ThinkProperties()
for _, name in pairs(self.PropertyProxyList) do
local currentValue = self["Get" .. name](self);
local oldValue = self.PropertyProxyCache[name];
if (currentValue != oldValue) then
local callback = self:GetNWVarProxy(name);
if (callback) then
callback(self, oldValue, currentValue);
end
end
self.PropertyProxyCache[name] = currentValue;
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment