jgm / pandoc

Universal markup converter
https://pandoc.org
Other
34.69k stars 3.39k forks source link

Add a helper for getting the list last item in Lua filters #10202

Closed CodeSandwich closed 1 month ago

CodeSandwich commented 1 month ago

The problem

In filters accessing the last item in a list is fairly common. The standard way to do it in Lua is to do list[#list], but it very quickly becomes unworkable when there are deeply nested lists. The filter ends up with monstrosities like blocks[#blocks].content[#blocks[#blocks].content] where the same identifiers are repeated multiple times, which hurts readability and increases the risk of introducing bugs. An alternative is to litter the code with intermediate variables, e.g. local content = blocks[#blocks].content and then content[#content].

The solution

The perfect solution would be for List to introduce a helper function List:last, which would return the last item or nil if the list is empty. The above example could be then expressed as blocks:last().content:last(), which is simple and elegant.

A more elastic approach would be to add List:get which would accept negative indexes, similarly to other languages but unlike Lua tables indexing. The above example could then be expressed as blocks:get(-1).content:get(-1).

CodeSandwich commented 1 month ago

Moved to https://github.com/hslua/hslua/issues/151