Big numbers in Pico-8
The Problem
In the fantasy console Pico-8, all numbers by default are 16:16 fixed point, which means if your player’s score goes above 32,767, the number will wrap around into the negative.
The Solution
There are a lot of suggested hacks around this, but since version 0.2.3, support for using 32-bit signed integers allows for a maximum value of 2,147,483,647 before you run into problems. You just need to change the way you handle your score variables.
When you want to add or subtract points, you have to bit shift the number to the right 16 bits.
points = 100
score += points>>16
damage = 20
score -= damage>>16
And then when you want to actually show the users score, you add the 0x2 format flag argument to the tostr() function so that it knows to read the bits correctly.
print(tostr(score, 0x2))
Additional notes
There’s a couple of gotchas with this. Multiplication by whole numbers should work fine, you don’t need to bit shift to do that. Same with division, but remember that you don’t have any decimals because you’re working with integers now, so fractions get rounded off.
You also can’t write something like score += 1000000>>16 because internally that million gets processed as a decimal and is subject to the size limit before it gets bit shifted. One way to get around that is to use the tonum() function to turn a string into a 32-bit signed int with the same format flag we used before.
score += tonum("1000000", 0x2)
print(tostr(score, 0x2))
- ← Previous
Advice on running a game jam