lua-users home
lua-l archive

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



On 5 Nov 2019, at 18:20, Viacheslav Usov <via.usov@gmail.com> wrote:

On Tue, Nov 5, 2019 at 6:04 PM Chris Smith <space.dandy@icloud.com> wrote:

> Thanks, that’s what I needed to know.  I can guarantee that references will be preserved, so this isn’t an issue.

If I understand the intent correctly, you would like to use a string returned by Lua after it was popped off the stack, on the account that it had previously been registered.

No, on the account that the string is still registered.  A Lua string will be created at the start of the Lua state and that string will remain referenced within Lua and thus never garbage collected.

I would recommend against this. This technique is brittle.

Other responses are suggesting that this is okay.

Note that the documentation warns explicitly: "Because Lua has garbage collection, there is no guarantee that the pointer returned by lua_tolstring will be valid after the corresponding Lua value is removed from the stack”.

Yes, but that is not a guarantee that it will be invalid either.  The point of my question was to determine what criteria would allow a guarantee to be made, either way.

I doubt you will gain much by popping prematurely, but I can guarantee that any eventual bugs will be a royal pain.

What do you mean popping prematurely?  A C function has to ensure the stack is balanced before returning, right?  And that means popping before returning whatever was pushed during the function call.  There is no way to directly grab a string value from Lua memory; you have to first push the string onto the stack then call lua_tostring() and as a consequence you then have to pop it back off before returning.

Chris

Chris Smith <space.dandy@icloud.com>