Adds Prompt library
John Smith

John Smith commited on 2021-310 00:40:44
Showing 2 changed files, with 52 additions and 2 deletions.


The `prompt.lua` module for manipulating prompts is added,
implementing the extraction of prompts from Rec-data (`Prompt:fromrecs`).
... ...
@@ -0,0 +1,50 @@
1
+--[[
2
+    a prompt consists of prompt text (with an answer-insertion point),
3
+    a correct answer, the review timestamp, and the review delay
4
+]]
5
+
6
+local Prompt = {}
7
+Prompt.__index = Prompt
8
+
9
+--[[
10
+    the answer-insertion point is indicated with a %A in the prompt text
11
+]]
12
+function Prompt:new(pt, ca, rts, rd)
13
+    local o = {}
14
+    setmetatable(o, self)
15
+    o.text = pt
16
+    o.ans = ca
17
+    o.time = tonumber(rts)
18
+    o.delay = tonumber(rd)
19
+    return o
20
+end
21
+
22
+function Prompt:__tostring()
23
+    return string.format("\"%s\" (\"%s\") %d+%d", self.text, self.ans, self.time, self.delay)
24
+end
25
+
26
+--[[
27
+    extracts prompts from a record-based deck
28
+    returns (on success) a table of Prompts
29
+    returns (on failure) nil
30
+]]
31
+function Prompt:fromrecs(recs)
32
+    local ret = {}
33
+    for _i, rec in ipairs(recs) do
34
+        -- only bother with records with PromptText
35
+        if rec.PromptText then
36
+            local opt = rec.PromptText[1]
37
+            local m, n = opt:find "%{[^%}]+%}"
38
+            local ctr = 1
39
+            while m do
40
+                local mpt = (opt:sub(1, m - 1) .. "%A" .. opt:sub(n + 1)):gsub("%{([^%}]+)%}", "%1")
41
+                table.insert(ret, Prompt:new(mpt, opt:sub(m + 1, n - 1), (rec.LastReview or {})[ctr], (rec.LastDelay)[ctr]))
42
+                m, n = opt:find("%{[^%}]+%}", n)
43
+                ctr = ctr + 1
44
+            end
45
+        end
46
+    end
47
+    return ret
48
+end
49
+
50
+return Prompt
... ...
@@ -7,7 +7,7 @@
7 7
 ]]
8 8
 
9 9
 --[[
10
-    maps text from a Recfile into a sequence of records
10
+    converts text from a Recfile into a sequence of records
11 11
     returns (on success) a table of tables of label-value-list pairs
12 12
     returns (on failure) nil
13 13
 ]]
... ...
@@ -79,7 +79,7 @@ local function text2recs(str)
79 79
 end
80 80
 
81 81
 --[[
82
-    maps a sequence of records into text for a Recfile
82
+    converts a sequence of records into text for a Recfile
83 83
     returns (on success) a string
84 84
     returns (on failure) nil
85 85
 ]]
86 86