Cloning Lua state

▼魔方 西西 提交于 2019-12-22 05:47:10

问题


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?


回答1:


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."




回答2:


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.




回答3:


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




回答4:


Notice, works with Lua 5.2 and above

You can just restrict access to this VM. Create one instance with all functions required, that will not depend on _G (global Lua state) and then create separate table for each client. That they will use as their global namespace. Setting a table as current _G is possible via _ENV. That's quite difficult topic to explain in one post. In short you prepare "virtual" _G for your new client and then just replace _G for the client's code. There is where I advice you to start.

Here's 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'll change _ENV for all further code. Good luck with experiments!

P. S. don't forget that you may set metatable for _ENV and _G tables and forbid changing that metatable. Lua is really flexible here.



来源:https://stackoverflow.com/questions/1383768/cloning-lua-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!