c++调用lua

      任务系统老肖早晨说要用lua脚本写,今天也瞌睡,于是在查资料的时候,困得眼睛都睁不开了,昏昏沉沉的。网上大部分的示例都是5.0之前的吧,所以关于lua_newstate的使用不会,于是怎么也找不到答案,瞌睡啊。晚上不瞌睡了,于是再试一次,发现终于搞好了。现在弄好了,贴上代码,以后看:

#include <iostream>
#include <stdio.h>

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

using namespace std;
#pragma comment(lib, "lua52.lib")
#pragma comment(lib, "luac.lib")

lua_State* runtime;

void* hover_allocator(void *ud,void *ptr,size_t osize,size_t nsize)
{
if(nsize==0){
if(ptr!=NULL) free(ptr);
return NULL;
}
else{
if(ptr==NULL) return malloc(nsize);
else return realloc(ptr,nsize);
}
}

int luaadd ( int x, int y )
{
int sum;

/* lua中的函数 */
lua_getglobal(runtime, "add");

/* 压入虚拟栈的第一个值 */
lua_pushnumber(runtime, x);

/* 第二个值 */
lua_pushnumber(runtime, y);

/* 调用传入的两个值,并返回一个结果 */
lua_call(runtime, 2, 1);

/*得到结果 ,由于返回类型不同 这里要显示的强制转换*/
sum = (int)lua_tointeger(runtime, -1);
lua_pop(runtime, 1);
return sum;
}

int main ( int argc, char *argv[] )
{
/* 初始化Lua */
runtime=lua_newstate(hover_allocator,NULL);
/* 载入Lua基本库 */
luaL_openlibs(runtime);
/* 运行脚本 */
luaL_dofile(runtime, "Lua1.lua");
///*调用lua函数*/
lua_getglobal(runtime, "aa");
lua_call(runtime, 0, 0);

/* 调用加法的方法 */
int sum = luaadd( 200, 50 );
printf("the sum is %d ", sum);
/* 清除Lua */
lua_close(runtime);
/* 暂停 */
cout << "Press enter to exit…" << endl;


getchar();
return 0;
}

对lua库的编译,如下:

cd src
cl /O2 /W3 /c /DLUA_BUILD_AS_DLL l*.c
del lua.obj luac.obj
link /DLL /out:lua52.dll l*.obj
cl /O2 /W3 /c /DLUA_BUILD_AS_DLL lua.c luac.c
link /out:lua.exe lua.obj lua52.lib
del lua.obj
link /out:luac.exe l*.obj
cd ..

ok,今天总算是做了点什么,不然怎么对得起一天三顿饭呢。以后晚上就早点睡吧,不能再看电影熬到半夜了。。。。go

原文地址:https://www.cnblogs.com/playerboy/p/3310749.html