Lua string to int

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Output

   string                                                                                                                                                                          
   number

Solution 4:

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.