Custom HUD causing Gmod to crash

So, I’ve been following a video tutorial series to get my feet wet in Gmod Lua scripting. I’ve gotten to a section on creating my own HUD. After some tweaks (the video was quite old, and some of the functions have changed) I have a working custom health HUD. However, the problem is, Garry’s Mod crashes a minute or two in with this custom health. From some testing, I’d guess something’s wrong when it calls the HUDPaint( ) function, or something related to drawing the HUD. I can’t figure out what is causing it to crash Garrys Mod. Can someone more experienced show me what I’ve done wrong? The code is in cl_init.lua for a dummy gamemode that doesn’t derive from sandbox or base. I’ll post the relevant HUD code below:

[lua]
function hidehud( myhud )
for k, v in pairs( {“CHudHealth”, “CHudBattery”} ) do
if( myhud == v ) then
return false;
end
end
end
hook.Add(“HUDShouldDraw”, “myHudHider”, hidehud);

function GM:HUDPaint( )
self.BaseClass:HUDPaint( )
local ply = LocalPlayer( );
local HP = ply:Health( );
local ARM = ply:Armor( );

surface.CreateFont("myNewFont",

{
font = "ScoreboardText",
size = 40,
weight = 500,
antialias = true
});

surface.SetTextColor( 0, 0, 255, 255 );
surface.SetTextPos( 20, 20 );
surface.SetFont("myNewFont");
surface.DrawText( HP );

end
[/lua]

Don’t create fonts inside the HUDPaint; you’ll eventually run out of memory and crash.

Call surface.CreateFont outside of the function.

You’re creating your font every frame, which would eventually cause your game to crash. Instead, create it in a separate function, and only call it once.
[lua]
function hidehud( myhud )
for k, v in pairs( {“CHudHealth”, “CHudBattery”} ) do
if( myhud == v ) then
return false;
end
end
end
hook.Add(“HUDShouldDraw”, “myHudHider”, hidehud);

local function CreateMyFont()
surface.CreateFont(“myNewFont”, {font = “ScoreboardText”, size = 40, weight = 500, antialias = true}) //Create the font
end

local shouldCreate = true
function GM:HUDPaint( )
if shouldCreate then
shouldCreate = false //Set it to false, so we don’t call this function again!
CreateMyFont() //Call the function
end
self.BaseClass:HUDPaint( )
local ply = LocalPlayer( );
local HP = ply:Health( );
local ARM = ply:Armor( );

surface.SetTextColor( 0, 0, 255, 255 );
surface.SetTextPos( 20, 20 );
surface.SetFont("myNewFont");
surface.DrawText( HP );

end
[/lua]

EDIT: Ninja’d :stuck_out_tongue:

I can’t believe I overlooked that possibility! No wonder it’s been crashing, thank you!