Skip to content

Instantly share code, notes, and snippets.

@thykka
Created November 13, 2023 10:24
Show Gist options
  • Save thykka/095c4a74b81d90fe4d4846cf0539fd78 to your computer and use it in GitHub Desktop.
Save thykka/095c4a74b81d90fe4d4846cf0539fd78 to your computer and use it in GitHub Desktop.
Serializer for PICO-8
--[[
Debug function for Pico-8
- Supports nested tables
- Colors output according to type
- Lists table values in alphanumeric key order
]]
function debug(val,x,y)
local oc=peek(0x5f25)--store original drawing color
local serialized=debug_serialize(val)
if x and y then
print(serialized,x,y) --use position when given
else print(serialized) end
color(oc)--restore color
end
function debugh(val)
debugh_active=true
printh(debug_serialize(val))
debugh_active=false
end
--should convert anything to a string
function debug_serialize(val,level)
level=level or 0
local vtype=type(val)
return debug_config.formatters[vtype](val,level);
end
--colorization function
_C=function(fg,bg)
if debugh_active then return '' end
local fgc=fg and debug_config.colors[fg] or false
local bgc=bg and debug_config.colors[bg] or false
return (fgc and ("\f"..fgc) or "")..(bgc and ("\b"..bgc) or "")
end
debug_config={
colors={
[""]=5,--default color
string="e",
number="c",
bool_f=8,
bool_t="b",
key="d",
other=8,
paren=5
},
formatters={
["nil"]=function() return _C"other".."[nil]" end,
["function"]=function() return _C"other".."[func]" end,
["string"]=function(str) return _C"string".."\""..str.."\"" end,
["number"]=function(num) return _C"number"..num end,
["boolean"]=function(bool) return _C(bool and "bool_t" or "bool_f")..(bool and "true" or "false") end,
["table"]=function(tbl,d)
--sort keys alphabetically
local keys={}
for k in pairs(tbl) do add(keys,k) end
sort(keys)
d+=1--increase indentation depth
local s=_C"paren".."{\n"
for k in all(keys) do
local v=tbl[k]
s=s.."\*"..d.." "--apply indentation
s=s.._C"key"..(
--show key names unless it's an array
type(k)=="string" and k.._C"".."=" or ""
)
--use recursion for printing the value
s=s..debug_serialize(v,d).._C""..",\n"
end
s=sub(s,0,#s-2).."\n"
d-=1--decrease indentation
if(d>0) s=s.."\*"..d.." "
s=s.._C"paren".."}"
return s
end
}
}
--[[
would be nice to just require these, but alas,
pico-8 seems to support neither #include
or require() for .lua files...
]]
function sort(arr, comp)
comp = comp or _sort_numbers
local function partition (a, lo, hi)
pivot = a[hi]
i = lo - 1
for j = lo, hi - 1 do
if comp(a[j], pivot) then
i = i + 1
a[i], a[j] = a[j], a[i]
end
end
a[i + 1], a[hi] = a[hi], a[i + 1]
return i + 1
end
local function quicksort (a, lo, hi)
if lo < hi then
p = partition(a, lo, hi)
quicksort(a, lo, p - 1)
return quicksort(a, p + 1, hi)
end
end
return quicksort(arr, 1, #arr)
end
function _sort_numbers(a, b)
return a < b
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment