Page 1 of 1

Help with textinput and numbers

Posted: Sun Oct 02, 2016 12:24 am
by ernelopez
Hi

I'm new to LÖVE and to programming, so I have a lot of newbie questions. My first question is about textinput. I want to get a number from user and make some comparisons with it (greater, etc). But it does not work as expected. Maybe I have to convert the string into int before making the comparisons?

Regards
Ernesto

Code: Select all

function love.load()
	pregunta = "Guess the number:"
    text = ""
    gane = false
    pistamayor = "A hint: it is greater."
	pistamenor = "A hint: it is lesser."
	pista = " "
end
 
function love.textinput(t)
    text = text..t
end

function love.update(dt)
	if love.keyboard.isDown('escape') then
		love.event.push('quit')
	end
	
	if love.keyboard.isDown('return') then
		if text == "40" then
			pregunta = "¡Well done!"
			pista = " "
			gane = true
		end
		if text > "40" then
			pista = pistamenor
		end
		if text < "40" then
			pista = pistamayor
		end
		text = ""
	end
end
 
function love.draw()
	love.graphics.printf(pregunta, 0, 0, love.graphics.getWidth())
    if gane == false then
    	love.graphics.printf(text, 0, 20, love.graphics.getWidth())
    end
    love.graphics.printf(pista, 0, 30, love.graphics.getWidth())
end

Re: Help with textinput and numbers

Posted: Sun Oct 02, 2016 2:16 am
by raidho36
Comparing strings like this will compare them by bytes, i.e. it doesn't even approaches string meaning and only uses each byte's numerical code as a number while comparing them. The dictionary is defined in alphabetical order so in some limited cases it will work but in general it wouldn't, especially if UTF-8 characters are involved because of variable character width.

What you want to do is to compare numbers. Text input needs to be converted to number for that.

Re: Help with textinput and numbers

Posted: Sun Oct 02, 2016 2:22 am
by ernelopez
Thanks a lot for the help!
raidho36 wrote:Text input needs to be converted to number for that.
How do I do that? :(

Regards
Ernesto

Re: Help with textinput and numbers

Posted: Sun Oct 02, 2016 2:36 am
by raidho36
You use "tonumber"? I dunno, I don't usually do this sort of thing. Try looking in the manual.

Re: Help with textinput and numbers

Posted: Sun Oct 02, 2016 9:34 am
by Zireael
Here's how to do this in your example:

Code: Select all

local int
int = tonumber(text)

if int > 40 then
pista = pistamenor
end

if int < 40 then
pista = pistamayor
end