Log In  

So if you've been around for a while, you've probably discovered that the PICO-8 call mid(a,b,c) can be used for clamping values to a range. The middle value in a set of (lo,val,hi) once you put them in order will either be val if it's between lo and hi, or if it's beyond, either lo or hi will be the middle. That's a clamp.

-- change volume but keep it in range
volume = mid(0, volume + volume_adj, 1)

It's convenient, if a little unintuitive. Some folks might alias the function to make it read better:

clamp = mid

-- change volume but keep it in range
volume = clamp(0, volume + volume_adj, 1)

Problem is, it's three args and each arg slows you down a bit. In most cases, one end of the range is 0. If you're writing a really tight inner loop, sometimes it'd be nice if you just had a function that assumed 0 for the top or bottom, instead of you having to pass it.

But wait! A useful bit of info is that PICO-8 API calls usually accept nil, or a missing arg, as if it were 0. For instance, x=cos() sets x to cos(0), or 1. Not useful for sin/cos, but...

Since mid() doesn't care what order the arguments are in, we can just leave off the third argument to implicitly pass it a 0 that way:

-- change volume but keep it in range
volume = mid(volume + volume_adj, 1)

For cycle counters out there, mid() with two local variables passed as args costs 5 cycles, vs 6 cycles with three.

And remember, it doesn't have to be the bottom end. If you're clamping -1..0, that works too:

-- change the decay rate
decay = mid(-1, decay + decay_adj)

Following on from this, if you know your value is moving towards 0, but must stop AT 0, then you can use the same trick with min() and max():

-- slow down until we stop (velocity==0)
velocity = max(velocity - friction)

-- swim back to the surface
depth = min(depth + desperation)

In both cases, you're implicitly passing a '0' as the second argument. This, again, saves you 1 cycle in each case, with single-arg min and max being 4 cycles instead of 5 for double-args.

P#49652 2018-02-25 05:46 ( Edited 2018-03-01 18:05)

Saves a token too!

P#49823 2018-03-01 08:53 ( Edited 2018-03-01 13:53)

Hey, good point. :)

Maybe @dddaaannn could add it to his minifier, if it's capable of noticing literal 0s.

P#49842 2018-03-01 13:05 ( Edited 2018-03-01 18:05)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-18 22:09:13 | 0.009s | Q:10