lua-users home
lua-l archive

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

> The thing to remember is that the lua_State, L, remembers all functions
> defined by your scripts; and that a function()...end sequence in the script is
> actually a *statement* that, when executed, defines a function.
> So by running the script *once*, you define all your functions. Once defined,
> you can call them; you just don't need to redefine them again.

I believe I am finally beginning to understand. I am now attempting to
re-write my C code to now call luaL_dofile only once.

> Actually, most of your code is right; it's just, ahem, not quite in the right
> order.
> The only thing you need to do is to split the code up so that luaL_dofile() is
> only called once, and everything from lua_getglobal() onwards is called three
> times. That should work. You also need to use lua_pcall() instead of
> lua_call(). If an error occurs in the Lua script, Lua will attempt to throw an
> exception using an internal longjmp-based mechanism; lua_pcall() will catch
> these. lua_call() doesn't, so if something goes wrong, Bad Stuff happens.

So I have noticed, about the Bad Stuff that is. I was also trying to
figure out why bad scripts killed the entire process. You have managed
to answer my next post before I was able to write it :-P

> You also need to be aware that const char* strings on the Lua stack only
> remain valid for as long as the Lua string is on the stack... so as soon as
> you call lua_pop(), ret dies.

Yes, I figured that out around day three, however notice that I use a
new pointer and assign the value to it instead of attempting to use
the original value:
  char *ret = (char *)lua_tostring(L, -1);

So even if the L pointer itself is deleted or resized 'ret' retains
it's value. Or so far it has. The results from 'ret' are instantly
translated and then discarded before the host process finishes it's
current cycle, so calling lua_pop directly after LUA_STR has not been
a problem. If I need to retain the value for future reference, I will
allocate a new buffer for it.

Thanks to everyone for their help with my problem, I'll re-lurk and
let you guys handle the real issues now :-)