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