function load_from_disk(filename)
local result = {}
local infile = io.open(filename)
if infile then
while true do
local line = infile:read()
if line == nil then break end
if line == '```lines' then -- inflexible with whitespace since these files are always autogenerated
table.insert(result, load_drawing(infile))
else
table.insert(result, line)
end
end
end
return result
end
function save_to_disk(lines, filename)
local outfile = io.open(filename, 'w')
for _,line in ipairs(lines) do
if type(line) == 'table' then
store_drawing(outfile, line)
else
outfile:write(line..'\n')
end
end
end
json = require 'json'
function load_drawing(infile)
local drawing = {h=256/2, points={}, shapes={}, pending={}}
while true do
local line = infile:read()
assert(line)
if line == '```' then break end
local shape = json.decode(line)
if shape.mode == 'line' then
shape.p1 = insert_point(drawing.points, shape.p1.x, shape.p1.y)
shape.p2 = insert_point(drawing.points, shape.p2.x, shape.p2.y)
end
table.insert(drawing.shapes, shape)
end
return drawing
end
function store_drawing(outfile, drawing)
outfile:write('```lines\n')
for _,shape in ipairs(drawing.shapes) do
if shape.mode == 'line' then
local line = json.encode({mode=shape.mode, p1=drawing.points[shape.p1], p2=drawing.points[shape.p2]})
outfile:write(line..'\n')
end
end
outfile:write('```\n')
end