lua-users home
lua-l archive

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


thanks a lot everybody! It is really nice to get a broad view of these possibilities. I hope all this information could help someone looking for a similar problem.

As for me, I will be using the Luiz Henrique de Figueiredo answer, which lets me load and run without even minding about loading everything at the beginning.

As posted by Luiz, the solution is the following:

int run_script(const char* name)
{
       int rc;
       lua_getglobal(L,name);
       if (lua_isnil(L,-1))
       {
               rc=luaL_loadfile(L,name);
               if (rc!=0) return rc;
               lua_pushvalue(L,-1);
               lua_setglobal(L,name);
       }
       rc=lua_pcall(L,...);
       return rc;
}


2009/9/23 Christopher Eykamp <chris@eykamp.com>
Actually, having read others' responses, I now see you were trying to run an entire script, not just a function, as I initially supposed.


Christopher Eykamp wrote:
Essentially, yes.  Here's a snippet from Bitfighter, a game I'm developing that uses Lua scripted robot players.  To get a robot's name, I call a function in the script called getName().  Here is the code I use:

 // Run the getName() function in the bot (will default to the one in robot_helper_functions if it's not overwritten by the bot)
 lua_getglobal(L, "getName");

 if (!lua_isfunction(L, -1) || lua_pcall(L, 0, 1, 0))     // Passing 0 params, getting one back
 {
    mPlayerName = "Nancy";
    logError("Robot error retrieving name (%s).  Using \"%s\".", lua_tostring(L, -1), mPlayerName.getString());
 }
 else
 {
    mPlayerName = lua_tostring(L, -1);
    lua_pop(L, 1);
 }

I do not claim to be a master at integrating Lua with C++, but there are several working examples of working integration in my codebase.  You can access it via Sourceforge, and the files of most interest will likely be robot.cpp and luaLevelGenerator.cpp.

Chris


zweifel wrote:
do you mean I can load a script called "melee.lua" and then call

lua_getglobal(L, "melee.lua");
lua_pcall(L, ...);

is that it?


2009/9/23 Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br <mailto:lhf@tecgraf.puc-rio.br>>

   > I see.. so I can load all scripts at the beginning or at least
   be sure to
   > load at least one time before calling the function.
   >
   > But I have to be sure that every script has a different
   function_name,
   > otherwise I would be unable to call it. Is not it?

   The script itself is an anonymous function.




--
God$ g++ -o earth earth.cpp -O3 -lanimals -lplants -lvirus

http://fog.neopages.org/



--
God$ g++ -o earth earth.cpp -O3 -lanimals -lplants -lvirus

http://fog.neopages.org/