[英]How to refactor repeating code in Pandoc lua filter
I am in the process of writing a Lua filter for Pandoc specifically targeting Pandoc generated LaTeX documents.我正在为 Pandoc 编写一个 Lua 过滤器,专门针对 Pandoc 生成的 LaTeX 文档。
Here is a small code snippet from my filter:这是我的过滤器中的一小段代码:
LATEX_CODES_FOR_TAGS = {
Span = {
sans = '\\sffamily ',
serif = '\\rmfamily ',
},
Div = {
-- Font Styles
sans = '\\begin{sffamily}',
serif = '\\begin{rmfamily}',
}
}
function Span(span)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == "Span" then
if span.classes:includes(class) then
table.insert(span.content, 1, pandoc.RawInline('latex', code))
end
end
end
end
return span
end
function Div(div)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == "Div" then
if div.classes:includes(class) then
local code_end = code:gsub('begin', 'end')
table.insert(div.content, 1, pandoc.RawBlock('latex', code))
table.insert(div.content, pandoc.RawBlock('latex', code_end))
end
end
end
end
return div
end
As you can see the code for the Div()
and Span()
functions are almost exactly the same, and therefore want to refactor the code.如您所见,
Div()
和Span()
函数的代码几乎完全相同,因此需要重构代码。
I have hitherto been unable to come up with a solution that makes the filter without the repeating code.迄今为止,我一直无法想出一种无需重复代码即可制作过滤器的解决方案。
I am still very new to Lua and wrapping my head around the concepts.我对 Lua 还是很陌生,并且对这些概念很感兴趣。
Thanks in advance.提前致谢。
Define the body of the loop as a separate function:将循环体定义为单独的 function:
local function create_handler(tag_str, handler_func)
return
function (obj)
for tag, code_for_class in pairs(LATEX_CODES_FOR_TAGS) do
for class, code in pairs(code_for_class) do
if tag == tag_str then
if obj.classes:includes(class) then
handler_func(obj, code)
end
end
end
end
return obj
end
end
Span = create_handler("Span",
function(span, code)
table.insert(span.content, 1, pandoc.RawInline('latex', code))
end)
Div = create_handler("Div",
function(div, code)
local code_end = code:gsub('begin', 'end')
table.insert(div.content, 1, pandoc.RawBlock('latex', code))
table.insert(div.content, pandoc.RawBlock('latex', code_end))
end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.