Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is a lone return statement valid Lua code?

In the pandoc introduction to filters the following code is presented as an "example of a Lua filter":

return {
  {
    Strong = function (elem)
      return pandoc.SmallCaps(elem.c)
    end,
  }
}

I have never seen a standalone return statement in Lua as shown in the example above. Furthermore I cannot see this syntax documented anywhere in the official reference.

Could anyone please let me know the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Whether this is valid Lua?
  • Where it is documented in the Lua docs?

>Solution :

Yes, this is valid Lua. Lua files or strings are called "chunks" and are basically functions and may thus contain return statements like any other function. Their arguments are accessible through the vararg ....

This is documented in the Lua 5.4 reference manual section on Chunks:

Lua handles a chunk as the body of an anonymous function with a variable number of arguments (see §3.4.11). As such, chunks can define local variables, receive arguments, and return values.


When starting a Lua file from the command line, ... will be the command line arguments. When manually loading strings or loadfileing files, you get the chunk returned as a function and can decide what you want to pass.


In fact it is considered good practice to return something from a required file rather than writing your library functions to the global namespace. return is in that case equivalent to JS export:

foo.lua:

return function()
    print("foo")
end

bar.lua:

local foo = require("foo")
foo()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading