PICO-8 Wiki
(Fixed formatting due to code being parsed as wiki formatting.)
Tags: Visual edit apiedit
(Oops, was wrong about a minimal clamp function. Edited to make it more minimal.)
Tags: Visual edit apiedit
Line 1: Line 1:
 
==Keeping a value between two other values==
 
==Keeping a value between two other values==
Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods use minimal tokens and characters. Which you use depends on how clear or concise you want your code.
+
Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods try to use minimal tokens and characters. Which you use depends on how clear or concise you want your code.
   
This clamp function relies on how Lua evaluates [[Lua#Logical_operators|Logical Operators]] and thus only uses 21 tokens and 63 characters.
+
This function uses only 15 tokens and 50 characters.
 
<pre>function clamp(a,b,c)
 
<pre>function clamp(a,b,c)
return a<b and b or (a>c and c or a)
+
return min(c,max(a,b))
 
end</pre>
 
end</pre>
 
This function is more readable, but it uses 22 tokens and 73 characters.
 
 
 
This function is more readable and uses only 22 tokens, but uses 73 characters.
 
 
<pre>function clamp(a,b,c)
 
<pre>function clamp(a,b,c)
 
if (a<b) return b
 
if (a<b) return b

Revision as of 21:46, 17 June 2017

Keeping a value between two other values

Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods try to use minimal tokens and characters. Which you use depends on how clear or concise you want your code.

This function uses only 15 tokens and 50 characters.

function clamp(a,b,c)
 return min(c,max(a,b))
end

This function is more readable, but it uses 22 tokens and 73 characters.

function clamp(a,b,c)
 if (a<b) return b
 if (a>c) return c
 return a
end