lua-users home
lua-l archive

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



Not having read the whole thread, but... I have snippet of code that seems like what everyone's after. Or.. is it? :)


const char* _glua_tolstring_safe( lua_State* L, int argn, uint* /* size_t* */ len_ref )
{
const char* ptr;

	// To bypass the int->str conversion side-effect, we make a local
	// copy of the stack entry, get a pointer to it, and remove it.
	// Even though the item is removed from stack, our pointer remains
	// valid until Lua does Garbage Collection (which is only after
	// GLUA_FUNC_END so this is safe :).

	_glua_pushvalue( L, argn );		// Makes [-1] a local copy
		{
		ptr= _glua_tolstring_raw(L,-1,len_ref);	  // may change the local copy
		}
	_glua_remove( L, -1 );			// Removes the copy from stack

	return ptr;		// Should remain valid until GLUA_FUNC_END.
}


Now... I hear you cry, it's not safe. This is another thread we've been up to a while back, namely whether Lua C API functions can cause garbage collection to be ignited, while a C function is running... I wish they did not :) ; that way the push-remove-butstilluse trick would be valid. It _is_ handy, and btw it does work in practise (at least, seems so...)

Perhaps I need to mark my code, that the commented behaviour actually is not guaranteed. **sigh** ;)
-asko


Daniel Collins kirjoitti 30.6.2006 kello 4.42:

Nobody has suggested what seems to me an obvious variation. lua_tostring leaves the original value unchanged, and pushes either nil or the string onto the top of the stack. That way you can copy the string if desired,
then pop it when you are finished with it.

- DC