269

How can I convert a string to an integer in Lua?

I have a string like this:

a = "10"

I would like it to be converted to 10, the number.

3
  • 9
    The precise link is the section on coercion: 5.1, 5.2. Commented Jun 9, 2012 at 18:53
  • 1
    Lua just does automatically conversion between strings and numbers. If you want ensure the type, use a = tonumber(a). Commented Feb 26, 2016 at 3:52
  • Lua is dynamically typed, however if you have a use for it you can always do tonumber() Commented Sep 18, 2023 at 17:53

16 Answers 16

416

Use the tonumber function. As in a = tonumber("10").

Sign up to request clarification or add additional context in comments.

1 Comment

In Lua 5.3, (64-bit default) integers are treated accordingly (lua.org/manual/5.3/manual.html): "A numeric constant with a fractional dot or an exponent denotes a float; otherwise it denotes an integer."
43

You can force an implicit conversion by using a string in an arithmetic operations as in a= "10" + 0, but this is not quite as clear or as clean as using tonumber explicitly.

3 Comments

Nope, it'll convert "10" to integer and then add 0 to it. (The lack of clarity is all the more reason to use tonumber instead, though!)
@Rena, there's no lack in clarity. + is always explicitly addition, .. - concatenation.
@lhf: auto coercion will only work on numbers. And comparison operators (== ~= < > <= >=) do not convert their arguments. And for performance reasons you should avoid relying on automatic coercion too much
13

All numbers in Lua are floats (edit: Lua 5.2 or less). If you truly want to convert to an "int" (or at least replicate this behavior), you can do this:

local function ToInteger(number)
    return math.floor(tonumber(number) or error("Could not cast '" .. tostring(number) .. "' to number.'"))
end

In which case you explicitly convert the string (or really, whatever it is) into a number, and then truncate the number like an (int) cast would do in Java.

Edit: This still works in Lua 5.3, even thought Lua 5.3 has real integers, as math.floor() returns an integer, whereas an operator such as number // 1 will still return a float if number is a float.

Comments

11
local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))

Output

   string                                                                                                                                                                          
   number

Comments

7

tonumber (e [, base])

tonumber takes two arguments, first is string which is converted to number and second is base of e.

Return value tonumber is in base 10.

If no base is provided it converts number to base 10.

> a = '101'
> tonumber(a)
101

If base is provided, it converts it to the given base.

> a = '101'
> 
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
> 

If e contains invalid character then it returns nil.

> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
> 
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171

I answered considering Lua5.3

Comments

5

say the string you want to turn into a number is in the variable S

a=tonumber(S)

provided that there are numbers and only numbers in S it will return a number, but if there are any characters that are not numbers (except periods for floats) it will return nil

Comments

5

The clearer option is to use tonumber.

As of 5.3.2, this function will automatically detect (signed) integers, float (if a point is present) and hexadecimal (both integers and floats, if the string starts by "0x" or "0X").

The following snippets are shorter but not equivalent :

  • a + 0 -- forces the conversion into float, due to how + works.
    
  • a | 0 -- (| is the bitwise or) forces the conversion into integer. 
    -- However, unlike `math.tointeger`, it errors if it fails.
    

Comments

5

It should be noted that math.floor() always rounds down, and therefore does not yield a sensible result for negative floating point values.

For example, -10.4 represented as an integer would usually be either truncated or rounded to -10. Yet the result of math.floor() is not the same:

math.floor(-10.4) => -11

For truncation with type conversion, the following helper function will work:

function tointeger( x )
    num = tonumber( x )
    return num < 0 and math.ceil( num ) or math.floor( num )
end

Reference: http://lua.2524044.n2.nabble.com/5-3-Converting-a-floating-point-number-to-integer-td7664081.html

Comments

5

Since lua 5.3 there is a new math.tointeger function for string to integer. Just for integer, no float.

For example:

print(math.tointeger("10.1")) -- nil
print(math.tointeger("10")) -- 10

If you want to convert integer and float, the tonumber function is more appropriate.

Comments

3

I would recomend to check Hyperpolyglot, has an awesome comparison: http://hyperpolyglot.org/

http://hyperpolyglot.org/more#str-to-num-note

ps. Actually Lua converts into doubles not into ints.

The number type represents real (double-precision floating-point) numbers.

http://www.lua.org/pil/2.3.html

Comments

2

You can make an accessor to keep the "10" as int 10 in it.

Example:

x = tonumber("10")

if you print the x variable, it will output an int 10 and not "10"

same like Python process

x = int("10")

Thanks.

Comments

2

Lua digital types are double precision types, which are implemented in luaconf. h in detail There are two general options:

  1. [Recommended use] The Lua script in version 5.3 contains the global.lua file, which includes the tonumber() and tostring() methods, which can realize the conversion of numbers and strings.
  2. math.tointeger() It can also be converted into numbers by using this method.

However, according to your actual scene, if it is only for calculation, Lua can be converted according to this operation symbol. eg

  s = "1" + 2; -- lua will convert "1" to 1
  print(s)

  s1 = "e" + 3; -- error
  print(s1)

more about lua,you can see lua official document

Hope to be useful to you and look forward to your reply,and looking forward to further communication with you!

Comments

2

You can use tonumber() to convert the string to a number, can be a float or an int.

Ex: tonumber("11") -- return: 11

Comments

1
Lua 5.3.1  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> math.floor("10");
10
> tonumber("10");
10
> "10" + 0;
10.0
> "10" | 0;
10

Comments

0

here is what you should put

local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)

output:

20

1 Comment

a = tonumber(stringnumber) is sufficent
0

Well, here's a good place to start. You can account for multiple cases by creating a function that wraps tonumber.

local function string_to_integer(str)
    -- Trim leading and trailing whitespace
    str = str:match("^%s*(.-)%s*$")

    -- Check for empty strings or invalid inputs
    if str == "" or tonumber(str) == nil then
        return nil, "Invalid input: not a number"
    end

    -- Attempt to convert to an integer directly
    local num = tonumber(str)

    -- Check if the number is an integer (no fractional part)
    if num == math.floor(num) then
        return num, nil
    else
        return nil, "Input is a valid number but not an integer"
    end
end

This is how you'd use it:

local str = "10"
local num, err = string_to_integer(str)
if err then
    print("Error:", err)
else
    print("Converted integer:", num)  -- Output: 10
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.