开发者

Overhead of copying lua functions

I have a lot of lua-script with the same name used for function name (intended for "entry point") and I want to run them. But I want to make it as fast as possible.

After some browsing/googling/thinking I've got two solution.

1., I have a main lua_State. I load the all necessary given and my own libs/functions "into" it. Next I lua_dump() the current lua-script's lua_State's function (with using linked list for chunck container), then I lua_load() it to the main lua_State and then lua_call() the main lua_State. With this solution I don't have to load all the libs for all the scripts. So the main lua_State is开发者_如何学Python an "environment". :)

2., I simply do the libs loading for all lua_State. And then lua_call() them.

The question would be that: Is even the first one logical correct? And if yes, which one would you use? Is there a better solution?

Thanks ahead and sorry for my English.

(And if the first one is really correct, are there some oblivious optimization possibility?)


As you put it, I don't see why you'd want more than 1 Lua state. If you have only one Lua state all overhead you'll have is loading the libs (once) and then loading the functions from the scripts you run (once, unless you need to 'refresh' them from the file). So simply have 1 state, and dofile the scripts.

If you really need those multiple lua_States, you could only load the libraries you need, as explained in the Lua Reference Manual, in the paragraph just above 5.1

There's also a nice freely available chapter on optimization of Lua code in Lua Gems Book.


I've recently done something similar and decided to use a single lua_State. I've custom-loaded every script file into its own environment via the use of the _ENV upvalue (generating a new environment for each as a copy of the global environment). This way the names won't conflict and I believe you can potentially run more scripts in parallel if you need that for whatever reason.

It works for my purposes as I need to access the functions in all the loaded scripts basically at random and at any time, but if all you need is to run them once then you can just load and execute them sequentially in the same lua_State.

Edit: I've noticed I've actually missed the point of the question. To answer: using a single lua_State will be faster if you need to load any standard libraries (the overhead is noticeable). If you are running each script only once you don't need to use lua_dump/lua_load, just do something like luaL_dofile followed by lua_pcall on the entry function, then move on (ie load the next file).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜