start writing results back to disk

I make some effort to preserve order, but deleting results and then
readding them appends to the bottom.
This commit is contained in:
Kartik K. Agaram 2023-10-17 16:16:37 -07:00
parent 0e5f69b099
commit f9e9b5e53c
8 changed files with 46 additions and 2 deletions

View File

@ -84,13 +84,18 @@ draw_data = function()
return
elseif v == nil then
Data[t1][t2] = 2 Data[t2][t1] = 0
add_result(t1, t2)
elseif v == 2 then
Data[t1][t2] = 0 Data[t2][t1] = 2
delete_result(t1, t2)
add_result(t2, t1)
elseif v == 0 then
Data[t1][t2] = nil Data[t2][t1] = nil
delete_result(t2, t1)
else
error('invalid value')
end
Global_state.next_save = Current_time + 3
end,
})
end
@ -101,4 +106,4 @@ draw_data = function()
App.color{r=0, g=0, b=0}
love.graphics.print(score(Data, t1), l+px, top+y*c+py)
end
end
end

View File

@ -1 +1,6 @@
Global_state = {} -- just anything we need across functions
-- just anything we need across functions
Global_state = {
button_handlers = {},
next_save = nil, -- if set, timestamp at which to save results to disk
results = {}, -- information about order in which to save to disk
}

View File

@ -1,9 +1,11 @@
load_results = function(filename)
results = {}
Global_state.results = {} -- cache ordering for when we modify Data
local f, err = App.open_for_reading(filename)
if err then error(err) end
for line in f:lines() do
local subject, object = line:match('^%s*(%S+)%s+beat%s+(%S+)%s*$')
table.insert(Global_state.results, {subject, object})
if subject == nil then
error('incorrect format: '..line)
end

6
0023-on.update Normal file
View File

@ -0,0 +1,6 @@
on.update = function()
if Global_state.next_save and Global_state.next_save < Current_time then
save_results()
Global_state.next_save = nil
end
end

10
0024-save_results Normal file
View File

@ -0,0 +1,10 @@
save_results = function()
if Results_filename == nil then return end
print('saving to '..Results_filename)
local f, err = App.open_for_writing(Results_filename)
if err then error(err) end
for _,result in ipairs(Global_state.results) do
f:write(('%s beat %s\n'):format(result[1], result[2]))
end
f:close()
end

6
0025-on.quit Normal file
View File

@ -0,0 +1,6 @@
on.quit = function()
if Global_state.next_save then
save_results()
Global_state.next_save = nil
end
end

3
0026-add_result Normal file
View File

@ -0,0 +1,3 @@
add_result = function(from, to)
table.insert(Global_state.results, {from, to})
end

7
0027-delete_result Normal file
View File

@ -0,0 +1,7 @@
delete_result = function(from, to)
for i=1,#Global_state.results do
if eq(Global_state.results[i], {from, to}) then
table.remove(Global_state.results, i)
end
end
end