(1) lua program
(2) C ++ program (headers)
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};class CLuaFn
{public:
CLuaFn(void);
~CLuaFn(void);
void Init (); // initialize the object pointer parameter Lua
void Close (); // Close Object Pointer Lua
bool LoadLuaFile (const char * pFileName); // load the specified file Lua
bool CallFileFn (const char * pFunctionName, int nParam1, int nParam2); // execute the function specified private Lua file:
lua_State * m_pState; // This is the State of Lua object pointer, you can file a Lua corresponds to a
};
(3) C ++ program (.cpp file)
#include "CLuaFn.h"
CLuaFn :: CLuaFn (void) {m_pState = NULL;}; // doing phrase
CLuaFn::~CLuaFn(void){};
// initialization function void CLuaFn :: Init ()
{
if (NULL == m_pState)
{
m_pState = lua_open (); // Returns a pointer to the object lua
luaL_openlibs (m_pState); // load all the basic Lua libraries you might use}
}
// close and release resources Lua objects void CLuaFn :: Close ()
{
if(NULL != m_pState)
{
lua_close(m_pState);
m_pState = NULL;
}
}
bool CLuaFn::LoadLuaFile(const char* pFileName)
{
nRet int = 0;
if (NULL == m_pState)
{
printf("[CLuaFn::LoadLuaFile]m_pState is NULL./n");
return false;
}
// load the file when the try to put the program initialization
nRet = luaL_dofile(m_pState, pFileName);
if (nRet != 0)
{
printf("[CLuaFn::LoadLuaFile]luaL_loadfile(%s) is file(%d)(%s)./n", pFileName, nRet, lua_tostring(m_pState, -1));
return false;
}
return true;
}
bool CLuaFn::CallFileFn(const char* pFunctionName, int nParam1, int nParam2)
{
nRet int = 0;
if (NULL == m_pState)
{
printf("[CLuaFn::CallFileFn]m_pState is NULL./n");
return false;
}
// verify your Lua function whether you currently loaded Lua file and the pointer to the function position lua_getglobal (m_pState, pFunctionName);
// push (sequence: parameter left to right): The first parameter lua_pushnumber (m_pState, nParam1);
// push: the second parameter lua_pushnumber (m_pState, nParam2);
// this function is performed, the 2 is the number of input parameters, return value is the number 1
nRet = lua_pcall (m_pState, 2, 1, 0);
if (nRet != 0)
{
printf("[CLuaFn::CallFileFn]call function(%s) error(%d)./n", pFunctionName, nRet);
return false;
}
if (lua_isnumber(m_pState, -1) == 1)
{
-ēnsumus lua_tonumber = int (m_pState, -1);
printf ( "[CLuaFn :: CallFileFn] i =% d. / n", -ēnsumus);
}
return true;
}
(4) C ++ program (main file)
#include "CLuaFn.h"int main(int argc, char* argv[])
{
CLuaFn LuaFn;
LuaFn.Init ();
LuaFn.LoadLuaFile("Sample.lua");
LuaFn.CallFileFn("func_Add", 11, 12);
getchar();
return 0;
}
Note: The program has been very detailed notes, I am not here to explain the code. After download and install lua, in vs2010 I would also like to introduce the appropriate library. Screenshot below: