#ifndef __LUA_FUNC_H__
#define __LUA_FUNC_H__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <error.h>
#include <iostream>
#include <list>
#include <string>
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#ifdef __cplusplus
}
#endif
/*
*获取lua文件句柄
*const char* lua_file 要加载的lua文件
*/
lua_State* LuaFileHandle(const char* lua_file)
{
if(lua_file == NULL)
{
printf("文件参数不能为空!\n");
return NULL;
}
lua_State* handle = luaL_newstate();
if(NULL == handle)
{
printf("LuaFileHandle->luaL_newstate fail!\n");
return NULL;
}
luaL_openlibs(handle);
//加载lua文件
luaL_dofile(handle, lua_file);
return handle;
}
/*
*关闭lua文件句柄
*lua_State* handle lua文件句柄
*reacher
*/
void CloseHandle(lua_State* handle)
{
if(NULL == handle)
{
printf("error!handle's null!\n");
return ;
}
lua_close(handle);
}
/*
*调用lua中无参无返回值函数
*lua_State* handle lua句柄
*const char* lua_func_name lua功能函数名
*/
bool CallNonParmNonRetFunc(lua_State* handle, const char* lua_func_name)
{
bool retStatus = false;
if((NULL == handle) || (NULL == lua_func_name))
{
printf("CallNonParmNonRet 形参有问题!\n");
return retStatus;
}
lua_getglobal(handle, lua_func_name);
//cpp 调用无参数的lua函数,无返回值
lua_pcall(handle,0,0,0);
retStatus = true;
return retStatus;
}
/*
*lua_State* handle
*const char* lua_func_name
*pstr
*/
bool CallNonRet(lua_State* handle, const char* lua_func_name,
const char* pstr)
{
bool retStatus = false;
if((NULL == handle) ||
(NULL == lua_func_name)||
(NULL == pstr) )
{
printf("CallNonRet 形参有问题!\n");
return retStatus;
}
/*
调用函数-》压入参数-》手动清理堆栈
*/
lua_getglobal(handle, lua_func_name);
lua_pushstring(handle,pstr);
lua_pcall(handle,1,0,0);
retStatus= true;
return retStatus;
}
/*调用lua中带形参带返回值
*lua_State* handle lua文件句柄
*const char* lua_func_name lua功能函数名
*... 不定lua形参
*/
string CallFunc(lua_State* handle, const char* lua_func_name,
list<string> parm_datas)
{
if((NULL == handle) ||
(NULL == lua_func_name) )
{
printf("CallFunc 形参有问题!\n");
return NULL;
}
string result_value;
lua_getglobal(handle, lua_func_name);
//参数从左到右压栈
for (list<string>::iterator it = parm_datas.begin();
it != parm_datas.end();
++it)
{
lua_pushinteger(handle, atoi(string(*it).c_str()));
}
lua_pcall(handle,2,1,0);
//获取返回值
result_value = lua_tostring(handle,-1);
return result_value;
}
#endif
lua_func.hpp
最新推荐文章于 2020-07-14 16:01:40 发布