lua-users home
lua-l archive

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


Hi,

David Morris-Oliveros wrote:
> [...] i'm getting very reproducible memory corruption
> _somewhere_. This is visible in a totally corrupt stack trace
> during reproducible crashes.
> [...]
>    ScriptInstance( lua_State* masterState ) {
>        m_SubLuaState = lua_newthread( masterState );
>    }

Have a look at the docs for lua_newthread():
"This function pushes the thread on the stack and returns
a pointer to a lua_State that represents this new thread."

The first part of the sentence is there for a good reason:
the Lua GC needs to know that the coroutine is still alive,
so you need to anchor it somewhere (table, registry, globals).
If not, then Lua will happily garbage collect your coroutine
and all kinds of strange things will happen. Just holding
a pointer to it in some C structure won't do.

In your case it's probably easiest to anchor a table at the
registry (use a unique lightuserdata key based on some dummy
static variable in your C program) and add your coroutines
there (e.g. indexed by a lightuserdata key of itself). Don't
forget to remove them in the destructor.

It might be a good idea to turn on assertions in the Lua core
while you are developing, too. See luaconf.h.

Bye,
     Mike