Friday Lua

A short while ago I was asked the following question,

“I use Trunk Notes to keep a log of my activities. I tag pages with ‘log’ and then have a page which lists all of those entries. It would be great if I could list the entries with the latest at the top.”

This isn’t something Trunk Notes can do out of the box; however with a bit of Lua scripting it’s easily achieved.

In my wiki I have the following pages tagged with log:

  • 18-11-2017
  • 22-11-2017
  • 24-11-2017
  • 10-12-2017

I have a page which contains the following:

{{tagged log}}

This lists the pages in alphabetical order, which isn’t what I want. Although my pages have dates as titles (European format) I would rather Trunk Notes used the created date as the title shouldn’t matter.

In order to do this I’m going to require the following to happen:

  • Get a list of all the pages tagged with log
  • Find out their created date
  • Order these pages by their created date
  • Output the list

Let’s have a go using Lua by adding the following into the page LuaLog.lua:

-- Get the titles of page which are tagged with log
page_titles = wiki.exprl('tagged', 'log')
-- Create an array of the page titles and created dates
pages = {}
for n, title in ipairs(page_titles) do
    page = wiki.get(title)
    table.insert(pages, { title = title, created = page.created })
end
-- Sort this by created in descending order (dates are just numbers)
table.sort(pages, function(page1, page2)
    return page1.created > page2.created
end)
-- Now prepare the Markdown list
output = ''
for n, page in ipairs(pages) do
   output = output .. " * [[" .. page.title .. "]]\n"
end
-- Return back to the calling page
return output

To use our new Lua function add {{lua LuaLog.lua}} to a page and you’ll see your list of tagged pages with the most recently created at the top.

Done!

If you have any cool uses for Lua in Trunk Notes let me know.