This section is more of a reference to how to use the math library in Lua. We aren’t going to go too into depth for each function. The math library can be divided up into several different classes of functions. We have rounding, trigonometrical, etc.
Math Constants
Constant | Description |
---|---|
math.huge | Infinity |
math.maxinteger | The biggest integer |
math.mininteger | The smallest integer |
math.pi | A constant for Pi |
Math Functions
Conversion and Rounding
Function | Description |
---|---|
math.abs( x ) | Returns the absolute value of x |
math.ceil( x ) | Rounds x up to the nearest int |
math.floor( x ) | Rounds x down to the nearest int |
math.fmod( x, y ) | Get the remainder from dividing x / y |
math.modf( x ) | Get the integer and fractional part for x, (2.5 = 2, 0.5) |
math.tointeger( x ) | Converts x to an integer, returns nil otherwise |
math.type( x ) | Gets the numerical type of x, either integer, float, or nil |
math.ult( x, y ) | Get a boolean if x as an unsigned int is less than y as an unsigned int |
Trigonometrical
Function | Description |
---|---|
math.acos( x ) | Gets the arc cosine in radians for x |
math.asin( x ) | Gets the arc sine in radians for x |
math.atan( x [, y] ) | Gets the arc tan in radians for x or x/y |
math.cos( x ) | Gets the cosine for radian value x |
math.deg( x ) | Converts angle x from radians to degrees |
math.rad( x ) | Converts angle x from degrees to radians |
math.sin( x ) | Gets the sine for radian value x |
math.tan( x ) | Gets the tangent for radian value x |
Random
Function | Description |
---|---|
math.random( [x [, y]] ) | Get a random number between 0 and 1, or 1 and x, or x and y (must be positive ints) |
math.randomseed( x ) | Seed the random number generator |
Comparative
Function | Description |
---|---|
math.max( x, … ) | Get the largest value between x and every other argument |
math.min( x, … ) | Get the lowest value between x and every other argument |
Exponential and Logarithmic
Function | Description |
---|---|
math.exp( x ) | Get ex |
math.log( x [, base ] ) | Get the natural logarithm for x, or a logarithm of base for x |
math.sqrt( x ) | Get x0.5 |
Simple Rounding
We have both math.floor( x ) and math.ceil( x ), but how do we round based on the fractional part of x being greater than or equal to, or less than 0.5? A quick trick for this is to do:
rounded = math.floor( x + 0.5 )
Exercises
We aren’t going to cover any specific details with these as they should be pretty self-explanatory. Try each one out and see what happens when you give it weird parameters. What happens with a negative value for x for math.sqrt( x )? What exactly does math.ult( x, y ) do for negative values? How could you do a true round function using math.ceil( x )?
View Comments (1)
very good well done thanks