[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: String lifetime (C API)
- From: "Beric Holt" <beric@...>
- Date: Tue, 28 Feb 2006 16:58:46 +1300
The best option is to strcpy the string if you intend to use it longer
than the life of the function. As David points out, this doesn't apply
if you are finished with it by the time the function ends and you pop
the value
Cheers
Beric Holt
http://buzzrick.emedia.net.nz
-----Original Message-----
From: David Morris-Oliveros [mailto:david.morrisoliveros@teambondi.com]
Sent: Tuesday, 28 February 2006 4:54 p.m.
To: Lua list
Subject: Re: String lifetime (C API)
I don't know the answer to this, but i would always make the assumption
that it's not safe. The Lua guys have always said that the
implementation of the VM is not something static, and might change in
the future, so, even if it may be safe to do so right now, i wouldn't
bet on it working in the future.
But, to my knowledge you can do this:
int SomeFunction( lua_State * L )
{
lua_getfield( L, 1, "name" );
const char * name = lua_tostring( L, -1 );
UseItInAFunction( name );
lua_pop( L, 1 );
return 0;
}
// David Morris-Oliveros
// Camera & Lua Coder
// david@teambondi.com
Chris wrote:
> Is it safe to use string values retrieved from a table even though the
> value is popped off the stack? For example:
>
> Lua side:
>
> table = { name="test1234" }
>
> C side:
>
> /* assume "table" is passed as argument to this function */
> int SomeFunction(lua_State* L)
> {
> lua_getfield(L, 1, "name");
> const char* name = lua_tostring(L, -1);
> lua_pop(L, 1);
>
> ... use "name" char* variable...
> }
>
> I know this is not always safe because the garbage collector might
> take the string after it is popped off this stack but in this case the
> string still exists in the table and will not be collected until
> "table" is collected (table is still on the stack). So is this
> example safe or is the string from lua_getfield actually a different
> string than the one in the table?
>
> --
> // Chris