We will calling Lua script function
Init()
from game engine.
1. Create Lua script function Init()
function Init()print("Now calling this function from game engine")end
which save as test_script.lua file
2. It will be call Lua functios GetLuaState() and LuaPCall of K3dLua class
#pragma onceextern"C"{#include <lua.h>#include <lualib.h>#include <lauxlib.h>}#include <iostream>usingnamespace std;class K3dLua{ lua_State *m_pLua; ///< Pointer to Lua statepublic: K3dLua () {// Open Lua state m_pLua = lua_open(); luaopen_base(m_pLua); luaopen_table(m_pLua); luaopen_io(m_pLua); luaopen_string(m_pLua); luaopen_math(m_pLua); } ~K3dLua() {// Close Lua stateif(m_pLua != NULL) { lua_close(m_pLua); } } lua_State *GetLuaState() {return m_pLua; }///\briefCallluascript///\param_iNumArgs Number of arguments///\param_iNumResults Number of results///\param_iErrFunc Error function indexint LuaPCall(constint _iNumArgs,constint _iNumResults,constint _iErrFunc) {return lua_pcall(m_pLua, _iNumArgs, _iNumResults, _iErrFunc); }///\briefDrawerrormessagetothekonsoleandcloseLuastate///\param_strFmt Input message stringvoid LuaError (constchar *_strFmt, ...) { va_list argp; va_start(argp, _strFmt); vfprintf(stderr, _strFmt, argp); cerr << endl; va_end(argp); } ... ... ...};
3. The funcion of game engine LF_Init() calling Lua script function Init()
///\briefCallLuafunctionInitvoid K3dVM::LF_Init(){// Function to be called lua_getglobal(ms_pLua->GetLuaState(), "Init");// do the call (0 arguments, 0 result) if (ms_pLua->LuaPCall(0, 0, 0) != 0) { ms_pLua->LuaError("error running function `Init': %s", lua_tostring(ms_pLua->GetLuaState(), -1)); }}