lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



Am 30.11.2012 um 00:43 schrieb Kevin Martin:


On 29 Nov 2012, at 23:20, Philipp Kraus wrote:

I would like to create for each of my individuals an own script, so I need for each script
one Lua state, do I? I would like to use one Lua state on one thread, so I would like
to use the Lua state with different Lua scripts. Can I do this?

If you write each script as a module

ie

local function run(args)
--do the calculation
--don't affect globals
end

return run

What do I return here? A reference to the lua function run !?


and then compile your scripts like this:

void addscript(lua_State *l, string name, string script) {
luaL_loadstring(l, script.c_str());
lua_pcall(l, 0, 1, 0);
lua_setglobal(l, name.c_str());
}

Then you have a global function for each script's run and you can do a lua_getglobal followed by a lua_call/lua_pcall to run it.

I do this in another example like:

lua_getglobal(m_lua, "main");

    

// push the first two parameters
lua_pushstring(m_lua, p_first.c_str());
lua_pushstring(m_lua, p_second.c_str());
lua_pushstring(m_lua, p_third.c_str());

    

// third parameter is an array
lua_newtable(m_lua);
for(std::size_t i=0; i < p_arrays.size(); ++i) {
   lua_pushnumber(m_lua, i+1);
   lua_pushstring(m_lua, p_array[i].c_str());
   lua_settable(m_lua, -3);
}

    

lua_call(m_lua, 4, 0); 

I call the "main" function in my lua script and push the arguments in it, so in my case I will do this with different
m_states for the different scripts

Phil