Playing with Lua
I’ve been asked recently for more tutorials on using Lua with Trunk Notes, and this morning I was asked:
“I want to include the previous page at the top of my current page.”
Using Lua this is an easy ability to add in Trunk Notes.
The starting point is working out how to get access to the last page. Trunk Notes has a function history
which returns a certain number of page titles that have been browsed recently. For example if you add {{history 1}}
to a page then it will output the name of the previous viewed page.
You can leverage Trunk Notes functions easily in Lua. So to get the name of the last page you viewed you can write:
history = wiki.exprl(‘history’, 1)
wiki.exprl
is a Lua function which takes the name of a Trunk Notes function followed by any arguments. There is also wiki.expr
, but this gives you Markdown rather than a Lua list which you can quickly parse.
Now that we have a list of recently viewed pages, in this case a list with only every 1 entry, we can write the full script:
– Get a list of pages from the history
history = wiki.exprl(‘history’, 1)
– Lua lists start from 1 (unusual for programming languages)
– So lets get the first entry in the list, i.e. the last page viewed
last_page_title = history[1]
– Get the contents of this page
page = wiki.get(last_page_title)
– Return the page contents, some empty lines and a horizontal line
return page.contents … ‘\n\n—\n\n’
Assuming you saved your script as Lastpage.lua then to add the content of the previous page to all your Trunk Notes pages add the following to the page Special:Header:
{{lua Lastpage.lua}}
Trunk Notes 4.5.1 will disable autocorrection and autocapitalisation whilst you are working on Lua scripts. Hopefully this update will be released in the next couple of weeks.
If you have any questions about the above leave them in the page comments below.