tags:

views:

637

answers:

3
+2  Q: 

Cloning Lua state

Folks, is there a way to clone a Lua state?

In my game application the initialization procedure of the Lua virtual machine is pretty heavy(about 1 sec, since many scripts are loaded at once). I have a separate Lua VM for each autonomous agent and once the agent is created its Lua initialization affects FPS pretty badly.

I'm thinking about the following schema: what about keeping "preforked" Lua state which is then simply cloned for each agent? Is it possible?

+3  A: 

You want to consider using Lua's coroutines for each autonomous agent, instead of a completely separate VM. Coroutines are a more lightweight solution, but may or may not be suitable for your application.

If you can't change the architecture, you might try LuaJIT. It might make the initialization fast enough for your purposes.

More options:

  1. Rings: "Rings is a library which provides a way to create new Lua states from within Lua. It also offers a simple way to communicate between the creator (master) and the created (slave) states."

  2. Pluto: "Pluto is a library which allows users to write arbitrarily large portions of the "Lua universe" into a flat file, and later read them back into the same or a different Lua universe."

ijprest
I was thinking about using coroutines however I'm afraid a fatal error in one coroutine will affect others that's why it's not option atm. Thanks for the links! I'm currently looking at LuaJIT and Rings. Rings seems to be a possible solution for my problem.
pachanga
Fatal error in one coroutine would not affect others in any way. As long as we're talking about Lua code -- user supplied stuff may do any damage it is programmed for of course.
Alexander Gladysh
+1  A: 

There's also Lanes (download, docs) and within the comparison to all similar products I know.

About Rings the comparison sheet says:

Rings offers separate Lua states, but no multithreading. This makes it simple, but it won't use more than one CPU core.

Note: The comparison sheet says Lanes would only marshal 'non-cyclic tables'. It does do cycles, and does marshall functions, upvalues etc. And it does the copies between Lua states as direct copies, not needing to stringify the contents in the middle. This makes it fast.

akauppi
+1  A: 

If you're on Linux, you may try lper, LPSM-based experimental library by one of Lua authors.

Alexander Gladysh
Yep, I'm on Linux, thanks for the link!
pachanga