Lua Cloning State

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

In my game application, the initialization procedure for the Lua virtual machine is quite difficult (about 1 second, since several scripts are loaded immediately). I have a separate Lua VM for each stand-alone agent, and as soon as the agent is created, its initialization by Lua greatly affects FPS.

I am thinking of the following scheme: how about preserving the β€œpre-Lua” state of Lua, which is then simply cloned for each agent? Is it possible?

+6
lua
source share
4 answers

You want to use Lua coroutines for each standalone agent, and not a completely separate virtual machine. Coroutines is an easier solution, but may or may not be suitable for your application.

If you cannot change the architecture, you can try LuaJIT . This can make initialization fast enough for your purposes.

Extra options:

  • Rings : "Rings is a library that provides a way to create a new Lua from within Lua, and also offers an easy way to communicate between the creator (master) and the created (subordinate) states.

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

+4
source share

There are also Lanes ( download , docs ) and in comparison to all similar products that I know.

The rings in the comparison sheet say:

Rings offer separate Lua states, but no multithreading. This makes it simple, but it will not use more than one processor core.

Note. The comparison sheet says that Lanes will only march on non-cyclic tables. It performs loops and performs marshall functions that increase values, etc. And copies of copies between Lua states are direct copies, without requiring to align the contents in the middle. This makes it fast.

+1
source share

If you are running Linux, you can try lper , LPSM, based on an experimental library from one of Lua's authors.

+1
source share

Please note that works with Lua 5.2 and higher.

You can simply restrict access to this virtual machine. Create one instance with all the necessary functions that will not depend on _G (global Lua state), and then create a separate table for each client. What will they use as their global namespace. Setting the table as the current _G is possible through _ENV. This is a rather complicated topic to explain in one post. In short, you are preparing a "virtual" _G for your new client, and then just replacing _G with the client code. Where I advise you to start.

Here is the point.

local _ENV = t -- change the environment. without the local, this would change the environment for the entire chunk

Just remove local and you will change _ENV for all subsequent code. Good luck with your experiments!

R. S. do not forget that you can set metatable for the tables _ENV and _G and prohibit changing this metatetable. Lua is very flexible here.

+1
source share

All Articles