Flr
Jump to navigation
Jump to search
flr( num )
- Returns the nearest integer at or below a number (its "floor").
- num
-
- The number.
- return-value
-
- The nearest integer at or below num.
If the given number is a fractional value between two integers, the lower integer is returned.
If the given number is already exactly an integer, it is returned as-is.
Examples
print(flr(5.9)) -- 5
print(flr(-5.2)) -- -6
print(flr(7)) -- 7
print(flr(-7)) -- -7
Technical notes
- PICO-8's number system is based on 32-bit fixed-point numbers, with 16 bits to the left of the decimal point and 16 bits to the right. This function effectively sets all bits to the right of the decimal point to 0. Therefore, its functionality can be done inline by using the & (and) operator with a mask which has the top 16 bits set to 1s and the bottom 16 bits set to 0s, i.e.
0xffff.0000
, which is actually just-1
in normal decimal notation.
Thus, these two lines are identical:print(flr(5.9)) -- 5 print(5.9 & -1) -- 5
This optimization has the benefit that it runs significantly faster in tight inner loops, but it has two drawbacks. One drawback is that it produces less-readable code. Another drawback that it is not portable to systems other than PICO-8, where numbers may not be stored in a format (e.g. floating-point) that accommodates this kind of bitmasking.
- It is also possible to use
value\1
to get the floor of a value, but beware that divides are very slow operations. It's useful for conserving characters in a tweetcart or some other kind of code golf, but otherwisevalue&-1
is the preferred inline optimization.