## Strings to numbers

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Techron
Prole
Posts: 13
Joined: Fri Mar 06, 2015 11:06 pm

### Strings to numbers

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.

BluBillz
Prole
Posts: 46
Joined: Tue Oct 29, 2013 6:02 pm

### Re: Strings to numbers

Try adding # before the variable. If it was in a table i believe it should work out like that.

arampl
Party member
Posts: 248
Joined: Mon Oct 20, 2014 3:26 pm

### Re: Strings to numbers

I thought tonumber(a) serves this purpose, and # is for element count in the table. Am I wrong?

ivan
Party member
Posts: 1606
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

### Re: Strings to numbers

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.

### Who is online

Users browsing this forum: No registered users and 16 guests