Is a lone return statement valid Lua code?
Asked Answered
C

1

7

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:

  • Whether this is valid Lua?
  • Where it is documented in the Lua docs?
Crore answered 16/6, 2022 at 12:5 Comment(2)
You can find all lua syntax in the chapter The Complete Syntax of Lua. It's called retstat or laststat.Evangelina
@Evangelina Perfect. Nice that they have the complete grammar on there...Crore
C
6

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()
Ciaracibber answered 16/6, 2022 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.