Log In  


Pico-8 doesn't provide a built-in way to sort arrays.

However it does provide a way to remove items from an array as well as a way to add them to a random position.

A lot of the time a full array-sorting function isn't needed; sometimes it's just enough to be able to insert one item into an already sorted array.

I did look around in the bbs but I didn't find a function for doing it, so here it is:

do
local lt=function(a,b)
 return a<b
end
function oadd(arr,obj,cmp)
 cmp=cmp or lt
 local l,r,m=1,#arr
 while l<=r do
  m=(l+r)\2
  if cmp(arr[m],obj) then
   l=m+1
  else
   r=m-1
  end
 end
 add(arr,obj,l)
 return l
end
end

The function figures out where to insert the item in an already sorted array (using the same algorithm as quicksort) and inserts the new item there.

For arrays of integers or strings it is a drop-in replacement for the built-in add function. The numbers will just be inserted in the right place so that they are sorted. The third optional parameter allows for using different comparation functions. Example:

local by_z=function(a,b) return a.z<b.z end
local obj1={z=14}
local obj2={z=5}
local arr={}
oadd(arr,obj1)
oadd(arr,obj2) -- arr should be {obj2,obj1} since obj2.z is smaller.

Attaching demo cart:

Cart #oadddemo-0 | 2025-02-18 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA




[Please log in to post a comment]