Lua string to int

后端 未结 12 1276
礼貌的吻别
礼貌的吻别 2020-12-23 08:39

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 n

相关标签:
12条回答
  • 2020-12-23 09:03

    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.

    0 讨论(0)
  • 2020-12-23 09:06

    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.
      
    0 讨论(0)
  • 2020-12-23 09:06
    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
    
    0 讨论(0)
  • 2020-12-23 09:07

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

    0 讨论(0)
  • 2020-12-23 09:07

    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

    0 讨论(0)
  • 2020-12-23 09:17

    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.

    0 讨论(0)
提交回复
热议问题