The more lua code I write in the pico-8, the more general purpose functions I wind up discovering. Here is my current utility library, I'll probably continue adding more as time progresses.

**Quick sort**

This one is pretty straight forward, you simply call it by providing a table and an optional comparator (for non-numeric lists), and it will in-place sort your table. It currently does not return anything, but it could me modified to return the table passed if you want to chain things.

-- Inplace quick sort function qsort(tbl, cmp, first, last) first = first or 1 last = last or #tbl cmp = cmp or function (x,y) return x - y end if (first >= last) then return end local pivot, pv, tail = first, tbl[pivot], last while pivot < tail do local tv = tbl[tail] -- Tail is smaller than the pivot -- Shuffle things around if ( cmp(pv, tv) > 0 ) then tbl[pivot], pivot = tv, pivot + 1 tbl[tail] = tbl[pivot] end tail = tail - 1 end tbl[pivot] = pv qsort(tbl, cmp, first, pivot - 1) qsort(tbl, cmp, pivot + 1, last) end |

Unpack is a useful function for converting a table into an argument list (similar to kargs in python), or assign a bunch of locals quickly:

IE: local x, y, z = unpack(vector) or print(join(",", unpack(numbers)))

-- Unpack table into spread values function unpack(y, i) i = i or 1 local g = y[i] if (g) return g, unpack(y, i + 1) end |

Enum does what you would expect, it's basically ipairs with an optional filter (in case you want to unpack the values, for example)

-- Enumerate and potentially filter a table function enum(t, filter) local i = 0 filter = filter or function (v) return v end return function() local o = t[i] i += 1 if (o) return i, filter(o) end end |

Join is my function for concatinating a list of arguments with a seperator. It's useful for displaying things like vectors.

-- Join arguments by a seperator function join(a, b, ...) x = {...} for i = 1,#x do b = b .. a .. x[i] end return b end |

[Please log in to post a comment]