lua-users home
lua-l archive

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



One handy trick, for doing dynamic string manipulation within C functions, involves pushing and/or combining strings using the Lua stack functions (concat etc.), getting a pointer to the result string (no C buffer needed), popping it out (no changes to stack) but still having the result string useful. Very neat, should be compulsory in C! ;P

-asko


Asko Kauppi kirjoitti 28.2.2006 kello 8.09:


But it _is_ safe, and it's actually a very, very, very :) nice trick to use in C/Lua interfaces.

It is safe to use the returned string, simply because the garbage collector never runs until you return from your C function back to Lua. Thus, you can: get a string, pop it, use the pointer.

If you still need the string later, after returning from the C function, then there's no guarantees (since the garbage collection eventually runs).

-asko

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?