You can convert strings to numbers using the function tonumber() . This takes a string argument and returns a number.
Lua has no integer type, as it does not need it. There is a widespread misconception about floating-point arithmetic errors and some people fear that even a simple increment can go weird with floating-point numbers.
“Type coercion” is the implicit or automatic conversion of a value from one type to another. In Lua, this is either from a string to a number or a number to a string. Lua will automatically convert the string and number types to the correct format in order to perform calculations.
You can easily convert a string to a number by using the tonumber() function. This function takes one argument (the string) and returns it as a number. If the string doesn't resemble a number, for example "Hello" , the tonumber() function will return nil .
Use the tonumber function. As in a = tonumber("10").
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.
local a = "10"
print(type(a))
local num = tonumber(a)
print(type(num))
Output
string
number
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With