Debian Codegraph @

texmf-dist/tex/lualatex/luaprogtable/luaprogtable-utility.lua

raw
1 inspect = require "inspect.lua"
2
3 function raise_error(...)
4 local arg = {...}
5 local description = "a luaprogtable package exception occured:\n" .. table.concat(arg, ", ")
6 tex.error(description)
7 error(description)
8 end
9
10 local _spacer = lpeg.S(" \t\f\v\n\r")
11 local _non_spacer = 1 - _spacer
12 local _stripper = _spacer^0 * lpeg.C((_spacer^0 * _non_spacer^1)^0)
13
14
15 function _lpt_strip(s)
16 return s and lpeg.match(_stripper,s) or ""
17 end
18
19 function _lpt_split(s, sep)
20 sep = lpeg.P(sep)
21 local elem = lpeg.C((1 - sep)^0)
22 local p = lpeg.Ct(elem * (sep * elem)^0) -- make a table capture
23 return lpeg.match(p, s)
24 end
25
26
27 function _lpt_tonumber(s)
28 local n = tonumber(s)
29 if n == nil then
30 raise_error(string.format("'{%s}' is not a valid number expression", s))
31 end
32 return n
33 end
34
35
36 function _lpt_parse_index_expr(expr)
37 local expr = _lpt_strip(expr)
38 local parts = _lpt_split(expr, ",")
39 local ret = {}
40
41 for i=1,#parts do
42 local subexpr = _lpt_strip(parts[i])
43
44 if subexpr:len() == 0 then
45 raise_error(string.format("empty field in index expression '%s'", expr))
46 end
47
48 local colon_pos = subexpr:find(":")
49 local str_l = ""
50 local str_r = ""
51
52 if colon_pos == nil then
53 str_l = subexpr
54 str_r = subexpr
55 else
56 local subsubexpr = _lpt_split(subexpr, ":")
57 str_l = _lpt_strip(subsubexpr[1])
58 str_r = _lpt_strip(subsubexpr[2])
59 if str_l:len() == 0 then
60 str_l = "1"
61 end
62 if str_r:len() == 0 then
63 str_r = "-1"
64 end
65 end
66
67 local n_l = _lpt_tonumber(str_l)
68 local n_r = _lpt_tonumber(str_r)
69
70 table.insert(ret, {n_l, n_r})
71 end
72
73 return ret
74 end
75
76 function _lpt_parse_shape(shape_expr)
77 local shape_expr = _lpt_strip(shape_expr)
78 local parts = _lpt_split(shape_expr, ",")
79 if #parts ~= 2 then
80 raise_error(string.format("invalid shape: '%s'", shape_expr))
81 end
82 local shape1 = _lpt_tonumber(parts[1])
83 local shape2 = _lpt_tonumber(parts[2])
84 if shape1 < 1 or shape2 < 1 then
85 raise_error(string.format("invalid shape: '%s'", shape_expr))
86 end
87 return {shape1, shape2}
88 end
89
90 function table.slice(tbl, first, last, step)
91 local sliced = {}
92
93 for i = first or 1, last or #tbl, step or 1 do
94 sliced[#sliced+1] = tbl[i]
95 end
96
97 return sliced
98 end
99
100 function table.find(tbl, item, index)
101 for i=index or 1, #tbl do
102 local tbl_item = tbl[i]
103 if tbl_item == item then
104 return i
105 end
106 end
107 return nil
108 end
109