Lua tointeger()
In Lua, the math.tointeger() function is a standard function that is part of the Lua math library. It is used to convert a given value to an integer, if the given value is convertible to an integer.
Note:
math.tointeger()was introduced in Lua 5.3. Earlier versions of Lua will not have this function as a standard part of theirmathlibrary.
Syntax
As tointeger() is a method that is a part of the standard Lua math library, it must be called as math.tointeger().
math.tointeger(mycoolvalue)
math.tointeger() returns an integer, if mycoolvalue is convertible to an integer. Otherwise returns nil.
Example 1
If the given value is an integer, math.tointeger() returns the given value, as in the following example:
print(math.tointeger(123))
This results in the following output:
123
Example 2
If the given value is not an integer but is convertible to an integer, the integer value is returned. This is shown in the following example:
print(math.tointeger('123'))
This will yield the following output:
123
Example 3
If the given value cannot be converted to an integer, math.tointeger() returns nil, as shown in the following example:
print(math.tointeger('I am not an integer value'))
This results in the following output:
nil
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
- Beginner Friendly.4 hours