function Init()print("Now calling this function from game engine")end
Který uložíme jako soubor test_script.lua
2. Budou se volat Lua funkce GetLuaState() a LuaPCall třídy K3dLua
#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. Funkce herního enginu LF_Init() volá Lua skript funkci 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)); }}