Search code examples
luapython-sphinxpandocrestructuredtext

Problems with lua filter to iterate over table rows


I'm trying to write a simply lua filter for pandoc in order to do some macro expansion for the elements in a ReST Table.

filter.lua

function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end

function Table(table)

    elems=pandoc.Table(table)["rows"]

    print(tablelength(table))
    for v in pairs(elems) do
        print(v) -- Prints nothings
    end
    return table
end

test.rst

======= =========
A       B 
======= =========
{{x}}   {{y}}
======= =========

Now, if I run pandoc.exe -s --lua-filter filter.lua test.rst -t rst the program says that there are 5 elements in elems, but the for loop is just skipped and I really don't know what I'm doing wrong here.

I'm very new to Lua and also know pandoc very litte. How can I iterate over the elements in elems?


Solution

  • Pandoc lua-filters provide the handy walk_block helper, that recursively walks the document tree down and applies a function to the elements that match the key.

    In the example below, we give walk_block a lua table (what's a map or dict in other languages) with only one key (the key Str), and the value of the table is the function to apply. The function checks for the braces, strips them and prepends foo.

    function Table(table)
      return pandoc.walk_block(table, {
        Str = function(el)
          if el.text:sub(1,2) == '{{' then
            txt = 'foo' .. el.text:sub(3, -3)
          else
            txt = el.text
          end
          return pandoc.Str(txt)
        end
      })
    end