Help with textinput and numbers

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
ernelopez
Prole
Posts: 4
Joined: Sun Oct 02, 2016 12:15 am

Help with textinput and numbers

Post 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
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Help with textinput and numbers

Post 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.
ernelopez
Prole
Posts: 4
Joined: Sun Oct 02, 2016 12:15 am

Re: Help with textinput and numbers

Post 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
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Help with textinput and numbers

Post by raidho36 »

You use "tonumber"? I dunno, I don't usually do this sort of thing. Try looking in the manual.
Zireael
Party member
Posts: 139
Joined: Fri Sep 02, 2016 10:52 am

Re: Help with textinput and numbers

Post 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
Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests