Built archives have commit hash and date added to version.
[QuestHelper.git] / pattern.lua
blobaac504a3c2fcb435e3a9bc907ee4680f86c54cc5
1 -- The following junk is for building functions to parse strings for various locales.
3 local varindex, varswap = 0, {}
5 local function replacePattern(p)
6 varindex = varindex + 1
7 local b, e, i = string.find(p, "(%d-)%$")
9 if i then
10 -- String contains an index.
11 p = string.sub(p, 1, b-1)..string.sub(p, e+1)
12 i = tonumber(i)
13 else
14 -- String doesn't contains an index, assume its index is the position we found it in.
15 i = varindex
16 end
18 varswap[i] = varindex
20 if p == "d" then return "(%d+)" end
21 if p == "s" then return "(.-)" end
23 -- Only know about strings and integers. Other types are broken.
24 assert(false, "Unknown pattern: %"..p)
25 end
27 -- Used to cache results, so we don't produce multiple functions for the same string.
28 local known_patterns = {}
30 function QuestHelper:convertPattern(pattern)
31 local result = known_patterns[pattern]
33 if result then
34 return result
35 end
37 while(table.remove(varswap)) do end
39 varindex = 0
41 local pat = string.format("^%s$", string.gsub(pattern, "%%(.-[%%%a])", replacePattern))
43 if varindex == 0 then
44 -- The string doesn't contain any variables.
45 result = self.nop
46 else
47 local func = "local function parse(input)\n"
48 local linear = true
50 for i = 1,varindex do
51 if varswap[i] ~= i then
52 linear = false
53 break
54 end
55 end
57 if linear then
58 -- All the arguments are in order, we can just return them.
59 func = func .. string.format("return select(3, string.find(input, %q))", pat)
60 else
61 -- The order has been changed, use temporary variables.
62 for i = 1,varindex do
63 func = func ..(i==1 and "local " or ", ")..("n"..i)
64 end
66 func = func .. string.format(" = select(3, string.find(input, %q))\n", pat)
68 for i = 1,varindex do
69 func = func ..(i==1 and "return " or ", ")..(varswap[i] and ("n"..varswap[i]) or "nil")
70 end
71 end
73 func = func .. "\nend\nreturn parse\n"
75 result = loadstring(func)()
76 end
78 known_patterns[pattern] = result
79 return result
80 end