Code only runs after lua refresh

I’ve been having this problem for a while and it’s really bugging me. For some reason, certain hooks or functions refuse to run until I modify the file then save it again, forcing it to refresh, then suddenly everything works perfectly. Would anyone care to explain to me why this happens? This is the code I’m attempting to run:
[lua]function GM:KeyPress( ply, key )

if ply:Team() == TEAM_SPEC then  
    local players = team.GetPlayers( TEAM_EASY )
    players = table.Add( players, team.GetPlayers( TEAM_MEDIUM ) )
    players = table.Add( players, team.GetPlayers( TEAM_HARD ) )
    players = table.Add( players, team.GetPlayers( TEAM_EXPERT ) )
    local spec_ply = ply:GetNWInt( "specply" )

    if key == IN_ATTACK then

        if #players < 1 then return end

        ply:SpectateEntity( players[(spec_ply+1)%(#players)+1] )
        ply:SetNWInt( "specply", (spec_ply+1)%(#players) )

    elseif key == IN_ATTACK2 then

        if #players < 1 then return end

        ply:SpectateEntity( players[(spec_ply-1)%(#players)+1] )
        ply:SetNWInt( "specply", (spec_ply-1)%(#players) )

    elseif key == IN_DUCK then

        ply.specmode = OBS_MODE_ROAMING

    elseif key == IN_JUMP then

        ply.specmode = (ply.specmode +1) % (#modes) +1
        ply:Spectate( modes[ply.specmode] )



No Lua errors, nothing. I try to put this function as it’s own local function (defined below the hook) and call it from within the hook and it says “attempt to call global function ‘X’”, even when I’m sure that the function names are correct. If it’s a global function, once again, nothing happens.

Some functions only work after initializing and it is most likely that you are trying to run them before the init and it’s refusing to work.

I’ve seen other people use this function in the exact same manner, eg. in TTT, yet this problem does not occur. I’ve tried encasing the hook inside an InitPostEntity hook, including it via another file, but nothing works. Does anyone know the best way to fix this?