DComboBox-assigning convars?

I have a DComboBox that is able to change a certain command in the way shown in the example below.



local ComboBox = vgui.Create( "DComboBox" )
	if GetConVarNumber( "example_command" ) == 1 then
		ComboBox:SetValue( "Command is true" )
	else
		ComboBox:SetValue( "Command is false" )
	end
ComboBox:AddChoice( "Make command true" )
ComboBox:AddChoice( "Make command false" )
ComboBox.OnSelect = function( ind, val, data )
	if val == 1 then
		RunConsoleCommand( "example_command", "1" )
	else
		RunConsoleCommand( "example_command", "0" )
	end
end


The only problem is that the ConVarNumber checking part only runs once, meaning if you change the convar while the ComboBox is open, the value of it will not change. I could put the checking statement in the paint function of this box, but that sounds a bit expensive to me. Any ideas?

This isn’t directly related to what you’re asking, but you appear to be missing the implicit “self” parameter in your OnSelect function.

You should either modify it to


ComboBox.OnSelect = function( self, ind, val, data )

or


function ComboBox:OnSelect( ind, val, data )

To your actual question, you can do something like the following using

cvars.AddChangeCallback:



ComboBox = ...
...
cvars.AddChangeCallback( "example_cvar", function( cvar, old, new )
    if ( !IsValid( ComboBox ) ) then return end

    ComboBox:SetValue( "Command is " .. ( tobool( new ) and "true" or "false" ) )
end, "something_unique" )