lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Thanks for the detailed explanation! Did I miss this description in my read of the reference manual (I did skip the grammar)?

This message composed at the mercy of thumbs and autocorrect.

On Nov 14, 2021, at 2:06 PM, Jonathan Goble <> wrote:

On Sun, Nov 14, 2021 at 2:52 PM Benjamin Riggs <> wrote:
Since it seems the interpreter literally wraps main chunks in a function call (I assumed load was just doing some back-end hand-waving), if the main chunk is only a single function declaration, will load then leave the declared function on the stack, or will it be wrapped in another layer of function call?

A chunk, no matter its contents, is always wrapped in an invisible vararg function. So a chunk that consists entirely of a function declaration will be wrapped in another function, and running the chunk will call and execute the wrapper function. If that wrapper function (i.e. the chunk) does not explicitly return a value, then it will return without a value (or nils if you ask for a specific number of values).

In that case, if the function declaration was global, the function will be available in the globals table, and you can fetch it that way. If it was declared as "local", it will be inaccessible to the code calling the wrapper function (as it was a local variable in the wrapper function). However, if a local function in a chunk is referred to by a global function or a function returned from a chunk, then the local function sticks around as an upvalue of the latter function(s), which makes a nice way to define private helper functions in a module.