Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


  • Having compiled Lua code in AgentClass.
  • Having lua_State only on AgentClass, setting a self variable in every AgentInstance update.
  • Other.
share|improve this question
up vote 3 down vote accepted

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, -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 );
share|improve this answer

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.

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.