[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Avoiding string duplication
- From: Chris Smith <space.dandy@...>
- Date: Wed, 6 Nov 2019 11:46:15 +0000
> On 6 Nov 2019, at 11:13, Viacheslav Usov <via.usov@gmail.com> wrote:
>
> Secondly, the registry entry might be intentionally or mistakenly overwritten.
>
> This is why I deem this brittle.
In this case I’m in control of both C and Lua code, so I am happy to assert that will never happen.
> > A C function has to ensure the stack is balanced before returning, right?
>
> No. It is "considered good programming practice", quoting the manual, and said only in the context of a caller, not a callee.
But I am the caller. The context here is that I’m using Lua for configuration. I load the configuration as a Lua file into the state and pcall() it, then the C code retrieves the values it needs from the Lua state. The configuration might have hundreds of string values and it would be a shame if I had to resort to strdup(lua_tostring()), duplicating and handling my own memory for such a trivial task. Leaving the strings on the stack would easily fill the stack, and I’d need more boiler plate to check that I hadn’t already left that particular string on the stack.
> No. "Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active." So a callee can leave the stack in whatever state. All it needs to do is indicate, via its return value, how many values at the top of the stack are its return values. "Any other value in the stack below the results will be properly discarded by Lua." Quoted sentences courtesy of the fine manual.
Yes, agreed, but again I’m talking in the context of C using Lua, not Lua using C.
Chris
—
Chris Smith <space.dandy@icloud.com>