Czech

OpenGL game

Calling Lua script from game engine.

Download engine sources (711,5kB)

06.11.23

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 once

extern "C" 
{
	#include <lua.h>
	#include <lualib.h>
	#include <lauxlib.h>
}

#include <iostream>
using namespace std;

class K3dLua
{
	lua_State *m_pLua;	///< Pointer to Lua state
		
	public:
		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 state
			if(m_pLua != NULL)
			{
				lua_close(m_pLua);
			}
		}
		
		lua_State *GetLuaState()
		{
			return m_pLua;
		}
		
		///\brief Call lua script
		///\param _iNumArgs Number of arguments
		///\param _iNumResults Number of results
		///\param _iErrFunc Error function index
		int LuaPCall(const int _iNumArgs,const int _iNumResults,const int _iErrFunc)
		{
			return lua_pcall(m_pLua, _iNumArgs, _iNumResults, _iErrFunc);
		}
		
		///\brief Draw error message to the konsole and close Lua state
		///\param _strFmt Input message string
		void LuaError (const char *_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()

///\brief Call Lua function Init
void 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));
	}
}


4. Tutorial how run Lua script find here.


home / opengl game


Valid XHTML 1.0 Transitional