Page 1 of 1

Text and variables

Posted: Wed Jan 02, 2019 10:55 am
by BobTheBuilder
Is there a way of setting a text (love.graphics.print("Hello)) to a variable? For example, when I click the "g" button, a variable will increase by 10 and will cause a text to change to 10.

Re: Text and variables

Posted: Wed Jan 02, 2019 10:43 pm
by Snaker1
Not sure if I understand your question but try:

Code: Select all

love.graphics.print("This is the variable g:"..tostring(g), 0, 0)
If you have a variable like g that is a number, you need to call the function tostring to convert it into a string.

To concatenate two strings together, you use the operator .. like:

Code: Select all

name = "Tom"
new_string = "Hello:"..name
Here is an example:

Code: Select all

function love.load()
	g = 0
end
function love.mousepressed()
	g = g + 1
end
function love.draw()
	love.graphics.print("g is: "..tostring(g), 0, 0)
end
This will increase g every time the mouse is clicked.

Now you only need to include checks for the mouse position, so that g gets only increased when the mouse is in a certain area. I am sure you can do that! :)

I hope this helps!

I think you are in the wrong sub forum, by the way. ;P

Re: Text and variables

Posted: Wed Jan 02, 2019 10:45 pm
by zorg
Hi and welcome to the forums;

yes, just use a variable, and print that.

Code: Select all

local v = 10
function love.keypressed(k)
if k == 'g' then v = v + 10 end
end
function love.draw()
love.graphics.print(v,0,0)
end
If that's not what you meant, then clarify further.

Also i hate being ninja'd by others :P

Edit:
Snaker1 wrote: Wed Jan 02, 2019 10:43 pm If you have a variable ... that is a number, you need to call the function tostring to convert it into a string.
That's a bit incorrect, lua itself usually coerces numbers into strings, the string concat. operator (..) certainly does.

Re: Text and variables

Posted: Wed Jan 02, 2019 11:13 pm
by Snaker1
zorg wrote: Wed Jan 02, 2019 10:45 pm That's a bit incorrect, lua itself usually coerces numbers into strings, the string concat. operator (..) certainly does.
Yes, true but I tried to teach him about how to explicitly convert a string into a number because that is pretty important as well. ;)

Good point though, that (..) can implicitly convert it. Should have mentioned that.