Comparison

util/interpolation.lua @ 6772:805baeca56b6

util.interpolation: Add support for filter functions
author Kim Alvefur <zash@zash.se>
date Fri, 07 Aug 2015 13:31:12 +0200
parent 6771:60957dd5b41b
child 10348:3852fc91b2fc
comparison
equal deleted inserted replaced
6771:60957dd5b41b 6772:805baeca56b6
22 local type, tostring = type, tostring; 22 local type, tostring = type, tostring;
23 local pairs, ipairs = pairs, ipairs; 23 local pairs, ipairs = pairs, ipairs;
24 local s_sub, s_gsub, s_match = string.sub, string.gsub, string.match; 24 local s_sub, s_gsub, s_match = string.sub, string.gsub, string.match;
25 local t_concat = table.concat; 25 local t_concat = table.concat;
26 26
27 local function new_render(pat, escape) 27 local function new_render(pat, escape, funcs)
28 -- assert(type(pat) == "string", "bad argument #1 to 'new_render' (string expected)"); 28 -- assert(type(pat) == "string", "bad argument #1 to 'new_render' (string expected)");
29 -- assert(type(escape) == "function", "bad argument #2 to 'new_render' (function expected)"); 29 -- assert(type(escape) == "function", "bad argument #2 to 'new_render' (function expected)");
30 local function render(template, values) 30 local function render(template, values)
31 -- assert(type(template) == "string", "bad argument #1 to 'render' (string expected)"); 31 -- assert(type(template) == "string", "bad argument #1 to 'render' (string expected)");
32 -- assert(type(values) == "table", "bad argument #2 to 'render' (table expected)"); 32 -- assert(type(values) == "table", "bad argument #2 to 'render' (table expected)");
38 if not value and name:find(".", 2, true) then 38 if not value and name:find(".", 2, true) then
39 value = values; 39 value = values;
40 for word in name:gmatch"[^.]+" do 40 for word in name:gmatch"[^.]+" do
41 value = value[word]; 41 value = value[word];
42 if not value then break; end 42 if not value then break; end
43 end
44 end
45 if funcs then
46 while value ~= nil and opt == '|' do
47 local f;
48 f, opt, e = s_match(block, "^([%a_][%w_.]*)(%p?)()", e);
49 f = funcs[f];
50 if f then value = f(value); end
43 end 51 end
44 end 52 end
45 if opt == '#' or opt == '%' then 53 if opt == '#' or opt == '%' then
46 if type(value) ~= "table" then return ""; end 54 if type(value) ~= "table" then return ""; end
47 local iter = opt == '#' and ipairs or pairs; 55 local iter = opt == '#' and ipairs or pairs;