Attach Lua script AI To C++ class!

Started by
6 comments, last by golgoth 18 years, 8 months ago
Hi all! What I m trying to do is to assign to each actor in a game environment a script ai! I m wondering if I must do: lua_State *m_lua; if ((m_lua = lua_open()) == NULL) { Trace("ERROR: LUA initialization failed!\n\n"); } else { Trace("TELL: LUA initialization successful!\n\n"); luaopen_base(m_lua); luaopen_table(m_lua); luaopen_io(m_lua); luaopen_string(m_lua); luaopen_math(m_lua); luaopen_debug(m_lua); RegisterFunction(); /// register all functions Int l_status = luaL_loadfile(m_lua, in_name.GetName()); lua_settop(m_lua, 0); if (l_status != 0) { lua_error(m_lua); } } to each of the script! Then update them individually each frame with: lua_pcall(m_lua, 0, 0, 0); or my first guest is to have only one lua_State instance and register all functions once and then keep track with a pointer to each luaL_loadfile... but I cant find the way to retrieve them... can anyone clear this up please? Is lua_open() should be call once (then register all possible functions once) or to all attached scripts? What is the ultimate way to do this with out unnecessary overheads? thx
Advertisement
one lua_State per ai dude
super genius
Alright!

so the whole process seams ok... but as a test ive tried:

lua_pcall(m_lua, 0, 0, 0);
lua_pcall(m_lua, 0, 0, 0);

the script is execute only once... why is that?

should i do:

_lua = lua_open())

every frame?
Before you execute any function with lua_pcall you must first push the function name onto the stack. You cannot just call lua_pcall(state, 0, 0, 0) and expect it to behave the same as it does when you first load the file.

You could just call load_file over and over but that is probably less efficient (way less).

Instead in your script make some func like

function ai_func()
-- do useful stuff here
end

then do something like this during your update:
lua_pushstring(L, "ai_func");
lua_pcall(L,0,0,0;

super genius
actually I made a mistake,

first push the func name, then get it, then do pcall

so it would be

lua_pushstring(L, "funcname");
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pcall(L,0,0,0;
super genius
O so interessting!

what about using:

lua_getglobal(m_lua, "in_function");
lua_pcall(m_lua, 0, 0, 0);

???

both way it works wonderfully!

thx everyone!
yes using lua_getglobal works equally well. In fact, it is the exact same. If you will look at lua.h you'll see lua_getglobal is just a macro
super genius
Alright!

thx alot! i think im all set!

This topic is closed to new replies.

Advertisement