public inbox archive for pandoc-discuss@googlegroups.com
 help / color / mirror / Atom feed
* Lua tip: list equality
@ 2022-04-13 21:14 Albert Krewinkel
  0 siblings, 0 replies; only message in thread
From: Albert Krewinkel @ 2022-04-13 21:14 UTC (permalink / raw)
  To: pandoc-discuss

Just want to share a little trick that I use to make some of my Lua
filters more readable.

Starting with pandoc 2.17, it became possible to use the 'equals'
operator on `List` values. E.g., a common pattern in my filters is to
check whether an element has just one specific class. Instead of using

    if #element.classes == 1 and #element.classes[1] == foo then
      ...
    end

it's now possible to write

    if element.classes == pandoc.List{foo} then
      ...
    end


This trick also works when checking whether an element has children of a
specific type.

    local List = pandoc.List
    function get_tag (x) return x.t end

    if element.content:map(get_tag) == List{'Math', 'Span'} then
      ...
    end


The list types must match, so if one was to check for an Emph with
content 'Quo vadis?' one would write

    local quo = pandoc.Inlines{
      pandoc.Str 'Quo,',
      pandoc.Space(),
      pandoc.Str 'vadis?'
    }

    function Emph (emph)
      if emph.content == quo then
        ...
      end
    end


List comparisons first check that both lists have the same type, and
then do an element-wise comparison.


-- 
Albert Krewinkel
GPG: 8eed e3e2 e8c5 6f18 81fe  e836 388d c0b2 1f63 1124


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2022-04-13 21:14 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-04-13 21:14 Lua tip: list equality Albert Krewinkel

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).