# How to share Lua script between instances?

I'm doing an agent based framework with C++ and Lua. I want to use Lua to code the Agent behaviour having an AgentClass class that have the name and source code and an AgentInstance class that have the lua_State. I want to have a few AgentClass instances during execution but hundreds or thousands of AgentInstance objects.

Is there any way to share the same lua script with different lua_State? Or Is there a better way to get hundreds of agents without too much performance penalty?

¿Options?:

• Having compiled Lua code in AgentClass.
• Having lua_State only on AgentClass, setting a self variable in every AgentInstance update.
• Other.

I have compile the lua code in the AgentClass object, and in the AgentInstance code I call funcions passing this pointer like:

lua_getfield( L, LUA_GLOBALSINDEX, SCRIPT_AGENT_NAME );
lua_getfield( L, -1, "init");
lua_getfield( L, LUA_GLOBALSINDEX, "Agent" );
lua_pushstring( L, "__obj" );
lua_pushlightuserdata( L, (void*)this );
lua_rawset( L, -3 );
auto ret = lua_pcall( L, 1, 0, 0 );


You only need a single lua_State for your game, so long as your scripts aren't making questionable changes to the standard tables. (If you are installing random scripts off the 'Net or something, you need tighter sandboxing; if you aren't, trust your devs to not be stupid.)

If you want globals to be stored per-entity, you can modify the metatable (or envionment, if using recent Lua) so calls to __index and __newindex map to a per-entity table, with fallbacks to the original shared global table for __index.

There are examples of this on the Lua Users' site last I checked, as well as a lot of code on the mailing list about the best way to do this.

Having multple Lua states wastes a lot of memory and slows things down because each agent access completely different sets of Lua memory blocks which is CPU cache unfriendly.

• thanks, I made something in the middle. Instead of one lua_state per object, I use one lua_State per agentclass. I have also take a look to that __index/__newindex solution and I'll apply it.
– Zhen
Feb 24 '13 at 15:12