Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

Is there an easy way in Lil to round a fraction to an integer?

I’m trying to render text to a canvas, centered within a given area. That’s easy enough, I can just measure the text string, subtract it from the available width, divide by 2, and use that as the left edge:

# Measure the text, minus the extra space at the end
textsize:canvas.textsize[text] - (canvas.font.space,0)
 
# Render the text centered
canvas.text[text pos+(size-textsize)/2]

If I’m drawing an even-width string into an even-width box, or an odd-width string into an odd-width box, that works perfectly. Otherwise, the coordinates wind up with a fractional part, which Decker truncates to 0, meaning that text that can’t be mathematically centred is shifted to the left.

That’s just mathematics and there’s not much to do about it, except that the strings I’m rendering tend to be Title Case, so they’re already visually weighted to the left. I think it would look a little better if fractional coordinates were rounded up rather than down, balancing the Title Case rather than reinforcing it, while leaving the mathematically-centred text (no fractional part) alone. Again that’s pretty easy:

canvas.text[text pos+(0.5,0)+(size-textsize)/2]

That works perfectly… unless the box I’m rendering into is also centred, which means it already has a 0.5 offset. In that case, the even-string-in-even-box and odd-string-in-odd-box wind up worse - instead of being rounded away, the extra 0.5 adds up to extra offset. I figure if I can round pos before using it in calculations, I can prevent errors from accumulating, something like this:

# I wish this worked!
pos:makeint[pos]

Playing around, it looks like I can probably do this with:

pos:bits.or[pos 0]

…but that seems a bit hacky. Is there a cleaner way to do this?

(+2)

You may be looking for the "floor" primitive? There's no corresponding "ceiling" primitive but you can take the negation of the floor of the negation:

 select value down:(floor value) up:(-floor-value) from .1*range 21
 
+-------+------+----+
| value | down | up |
+-------+------+----+
| 0     | 0    | 0  |
| 0.1   | 0    | 1  |
| 0.2   | 0    | 1  |
| 0.3   | 0    | 1  |
| 0.4   | 0    | 1  |
| 0.5   | 0    | 1  |
| 0.6   | 0    | 1  |
| 0.7   | 0    | 1  |
| 0.8   | 0    | 1  |
| 0.9   | 0    | 1  |
| 1     | 1    | 1  |
| 1.1   | 1    | 2  |
| 1.2   | 1    | 2  |
| 1.3   | 1    | 2  |
| 1.4   | 1    | 2  |
| 1.5   | 1    | 2  |
| 1.6   | 1    | 2  |
| 1.7   | 1    | 2  |
| 1.8   | 1    | 2  |
| 1.9   | 1    | 2  |
| 2     | 2    | 2  |
+-------+------+----+
(+2)

…oh! Well, I feel silly now. I searched the docs and this forum for “round” and “truncate”, but I never thought to search for “floor”. Thanks!