lua_func.hpp

#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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值