[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua pattern for a main chunk to leave a function on the stack
- From: Andrew Gierth <andrew@...>
- Date: Sun, 14 Nov 2021 20:41:12 +0000
>>>>> "Benjamin" == Benjamin Riggs <riggs@entropicengineering.com> writes:
Benjamin> Thank you; this is very helpful.
Benjamin> I didn’t expect that a return statement from a main chunk
Benjamin> would leave the returned value(s?) on the stack.
To be precise, what's left on the stack depends on how you called the
chunk. Functions like luaL_dofile or luaL_dostring call the compiled
chunk with lua_pcall(L, 0, LUA_MULTRET, 0) which means that any number
of return values is allowed (you have to look at the change in the value
of lua_gettop(L) to see how many there were); but if you do a separate
lua_load and lua_pcall yourself, you can specify how many return values
you want (and also pass arguments if you want to, which the chunk can
access via the ... token).
Benjamin> Since it seems the interpreter literally wraps main chunks in
Benjamin> a function call (I assumed load was just doing some back-end
Benjamin> hand-waving), if the main chunk is only a single function
Benjamin> declaration, will load then leave the declared function on
Benjamin> the stack, or will it be wrapped in another layer of function
Benjamin> call?
What lua_load() (and its variants) leaves on the stack is always a
wrapper around the content of the loaded chunk, and it's always an
anonymous vararg function (and in 5.2+ it always has a single upvalue
named _ENV, whether it actually uses it or not - this is important for
sandboxing, since you can use lua_setupvalue to set the chunk's _ENV to
the correct sandbox environment before calling it).
--
Andrew.