How to make convars trigger functions?

Basically, the convar I’ve made doesn’t respond to its arguments. If I put “sv_maintenance 1” or “sv_maintenance 0” in the server console, nothing happens.

Note: The lua file is placed here: lua/autorun.

How to make the convar respond to arguments?



--Variables--
local hostname_maintenance = "[DJ] Servers | Maintenance |"
local hostname_normal = (GetConVarString("hostname"));

--Start of code--
CreateConVar("sv_maintenance", "0", FCVAR_SERVER_CAN_EXECUTE, "Enable maintenance mode.")

function MaintenanceThink()
	if GetConVar("sv_maintenance"):GetBool() then
		--maintenance_mode = "true"
		RunConsoleCommand("hostname", hostname_maintenance)
		PrintMessage(HUD_PRINTTALK, "Maintenance mode: On")
	else
		--maintenance_mode = "false"
		RunConsoleCommand("hostname", hostname_normal)
		PrintMessage(HUD_PRINTTALK, "Maintenance mode: Off")
	end
end

if SERVER then
	MaintenanceThink()
end


You’re only calling MaintenanceThink once. Use

cvars.AddChangeCallback. Also, cache your convar like this instead of doing it inside the function:


local sv_maintenance = CreateConVar(...)

function MantenanceThink()
   if sv_maintenance:GetBool() then
      -- code
   end
end

Like this?



--Start of code--
local sv_maintenance = CreateConVar("sv_maintenance", "0", FCVAR_SERVER_CAN_EXECUTE, "Enable maintenance mode.")

function MaintenanceThink()
	if sv_maintenance:GetBool() then
		RunConsoleCommand("hostname", hostname_maintenance)
		PrintMessage(HUD_PRINTTALK, "Maintenance mode: On")
	else
		RunConsoleCommand("hostname", hostname_normal)
		PrintMessage(HUD_PRINTTALK, "Maintenance mode: Off")
	end
end


Where do I put:


 cvars.AddChangeCallback("sv_maintenance", MaintenanceThink) 

You should use the value sent in from cvars.AddChangeCallback instead of repolling the convar. Like this:


CreateConVar(...)

local enabled = false

cvars.AddChangeCallback("sv_maintenance", function(_, _, newval)
   newval = tonumber(newval)
   
   if (newval) then -- Valid number
      if (not enabled and newval > 0) then -- Changed from false to true
         enabled = true
         -- Enabled code here
      elseif (enabled and newval == 0) then
         enabled = false
         -- Disabled code here
      end
   end
end)

Also, I meant in general that you should not use GetConVar in a function, but cache it outside instead.

sv_maintenance 1 works, changing the hostname to what is set previously in the code. sv_maintenance 0 works but the hostname doesn’t set to what I was expecting.

How do I set the server’s starting hostname as a variable? Or how do I pull the hostname from server.cfg into the lua file?

Thanks for the help :stuck_out_tongue:

[editline]18th December 2016[/editline]

I have fixed this issue, thanks for the help code_gs!