Code Crashed Gmod

Hey guys, I’ve written a small block of lua code in a very simple gamemode that I’ve made. It is supposed to wait until a user holds down the space button and then it will repeatedly increase a vector every second until the person releases the space key or until it reaches the maximum vector which I have set. It then adds this vector as a velocity to the player.

But it crashes gmod every time I hold the space button.
Can anyone figure out why? Here’s the code:

function GM:Move( ply, mv )

if ( mv:KeyPressed( IN_JUMP ) ) then
local jump = Vector(0, 0, 0)

while( mv:KeyDown( IN_JUMP ) and jump ~= Vector(0, 0, 2500 )) do
timer.Simple( 1, function() jump = jump + Vector(0, 0, 1) end )
end

local vel = mv:GetVelocity()
vel = vel + jump
mv:SetVelocity( vel )

return true;
end

end

You have an “infinite” loop.

Uhm okay thanks could you tell me which part of the code is looping infinitely and why? I’m pretty new to this.

[lua]

while( mv:KeyDown( IN_JUMP ) and jump ~= Vector(0, 0, 2500 )) do
timer.Simple( 1, function() jump = jump + Vector(0, 0, 1) end )
end

[/lua]

The very moment that you press your spacebar key, that loop will start going.

The game can’t continue until a loop stops, and thus it can’t detect that your spacebar has been released because that loop is all it’s focusing on, if that makes any sense.

Also your logic is flawed. Assuming that the loop wasn’t a problem, you’d still be constantly creating new timers that would then all start triggering rapidly after 1 second.

What you want to do is have a new timer start after the previous timer has stopped, which isn’t what you’re doing right now.

Imagine this (it’s similar to what you’re doing):
[lua]
for i = 1, 10 do
timer.Simple( 1, function() print( “hi” ) end )
end
[/lua]

You’re instantly creating 10 independent timers which will all trigger after 1 second. So, when that code is ran, there’ll be silence for 1 second and then there’ll be printed 10 “hi” messages.