lua-users home
lua-l archive

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


Can you give me an example of a thread safe host function that will
execute a script inside of a Lua thread with a *copy* of the globals
table?

For example, I have a Delphi function called RunScript() that accepts
a lua script filename and then runs it.  It looks something like this:

procedure RunScript(filename : String);
var
  newThread : lua_State;
begin
  newThread := lua_newthread(_luaVM);
  lua_dofile(newThread, pchar(filename));
end;

First off, I'm not sure if that function is thread safe (meaning lots
of threads will be running it at the same time) and secondly I'm not
sure what I need to add to create a new global table with a *copy* of
the old global table (or a reference to it via __index).

Sorry for being a pain...  I really, really do appriciate all of the help.

Also, happy holidays!

On 12/22/05, Rici Lake <lua@ricilake.net> wrote:
>
> On 22-Dec-05, at 4:04 PM, John Klimek wrote:
>
> > Thanks for the information!
> >
> > So... threads share the global environment with the parent lua_state.
> > Therefore, if I change a global variable in my thread, it WILL also
> > change in the parent lua_state.
> >
> > How can I prevent this and give my thread it's own global environment?
>
> As I mentioned in the wiki page, you can push a table onto the stack
> and then:
>
>    lua_replace(L, LUA_GLOBALSINDEX);
>
> However, it's not as simple as that. The table actually has to have all
> sorts of stuff in it, like the base library functions and the standard
> library tables (at least, the ones you want to use) plus any extension
> libraries you've defined, etc.
>
> One way to accomplish all that is to use an __index metamethod so that
> your new globals table inherits from the base globals table. However,
> you still need to have some stuff in the globals table because Lua
> (5.0.2 anyway) relies on things being in the globals table, and in many
> cases it does a rawget rather than a gettable, so you generally want to
> put baselib into the new globals table anyway.
>
> > Also,  every time I create a thread  (in Delphi using  newThread =
> > lua_newthread(_luaVM)), the thread seems to remain on the stack even
> > after my lua_dofile() is finished.
> >
>
> Yes, indeed. See lua_pop()
>
> > So, after creating five or six threads I have ALL of them on top of
> > the stack in my main program.  The manual says to use
> > lua_closethread() after calling lua_dofile() but lua_closethread()
> > doesn't exist.
>
> What manual would that be? .... lua_dofile() is deprecated, as well. See
> luaL_loadfile() and lua_pcall()
>
>
>