Page 1 of 1

Löve crashes when trying to identify key presses

Posted: Sat Jan 18, 2014 8:32 pm
by fiskero94
Hello there, I am quite new to Löve and Lua, I've only worked with Arduino before. I'm trying to make Löve register the keys W, A, S and D, however Löve crashes when either key is pressed. This is the code:

Code: Select all

-- Controls Pressed
function love.keypressed(key)

	while key == 'w' do
		w_down = true
	end
	
	while key == 'a' do
		a_down = true
	end
	
	while key == 's' do
		s_down = true
	end
	
	while key == 'd' do
		d_down = true
	end
	
end

-- Controls Released
function love.keyreleased(key)

	if key == 'w' then
		w_down = false
	end
	
	if key == 'a' then
		a_down = false
	end
	
	if key == 's' then
		s_down = false
	end
	
	if key == 'd' then
		d_down = false
	end
	
end

-- Draw
function love.draw()

	while w_down == true do
		love.graphics.print('W is pressed', 400, 300)
	end
	
	while a_down == true do
		love.graphics.print('A is pressed', 400, 300)
	end
	
	while s_down == true do
		love.graphics.print('S is pressed', 400, 300)
	end
	
	while d_down == true do
		love.graphics.print('D is pressed', 400, 300)
	end
	
end
Thanks :)

Re: Löve crashes when trying to identify key presses

Posted: Sat Jan 18, 2014 9:15 pm
by Roland_Yonaba
You are trapping Löve control flow into a endless while loop, hence the crash.
Replace those "while-do-end" with "if-then-end" clauses.
Note: This might help!

Re: Löve crashes when trying to identify key presses

Posted: Sat Jan 18, 2014 10:19 pm
by fiskero94
Thank you, the code works now, however now I am even more confused about the use of "while". Is there any guides on this?

Re: Löve crashes when trying to identify key presses

Posted: Sat Jan 18, 2014 10:28 pm
by DaedalusYoung
A while loop keeps repeating while the condition is true.

Code: Select all

x = 1
while x < 5 do
    print(x)
    x = x + 1
end
This will loop 4 times, after which x is 5 and the condition is no longer true.

See also:
* https://en.wikipedia.org/wiki/While_loop
* http://www.lua.org/pil/4.3.2.html

Re: Löve crashes when trying to identify key presses

Posted: Sun Jan 19, 2014 8:59 am
by Plu
It's important to understand that your whole game is already running inside a while loop, one that constantly calls love.update and then love.draw. The only way for something to appear on the screen is if both love.update and love.draw are completed, because after that it draws everything. So you must not trap these functions in an infinite loop.