Strings to 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
Techron
Prole
Posts: 13
Joined: Fri Mar 06, 2015 11:06 pm

Strings to numbers

Post by Techron »

Hello!
I have this issue when I am trying to load a save file. It gives me an error saying that I cannot compare a string to a number, and I obviously know that's the problem. Is there any way I can convert a string to a number, or possibly declaring the variable a number in the save? Sorry if that sounded confusing, this is my first forum post.
User avatar
BluBillz
Prole
Posts: 46
Joined: Tue Oct 29, 2013 6:02 pm

Re: Strings to numbers

Post by BluBillz »

Try adding # before the variable. If it was in a table i believe it should work out like that.
User avatar
arampl
Party member
Posts: 248
Joined: Mon Oct 20, 2014 3:26 pm

Re: Strings to numbers

Post by arampl »

I thought tonumber(a) serves this purpose, and # is for element count in the table. Am I wrong?
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Strings to numbers

Post by ivan »

You can use "tonumber".

Code: Select all

assert(type(s) == "string", "input must be a string")
n = tonumber(s)
assert(type(n) == "number", "conversion failed!")
Should work with decimal numbers or hex numbers.
Returns nil if it fails to convert the number.

Turns out that "#s" for strings is used to get the number of bytes, similar to "string.len":

Code: Select all

a = "012345"
assert(#a == 6, "string is not 6 bytes long!")
The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).
Note that for UTF8 strings, the number of bytes may not equal the number of characters.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 79 guests