在代码中加入运行lua脚本的功能
在程序里添加脚本功能,可以运行我们的test.txt脚本.
好处就是只在程序里写函数,而逻辑全部放到脚本里写,下次想改逻辑,只用改脚本,不然每次都得重新修改编译源代码。
通过lua把L_haha注册成一个能在脚本里使用的函数名txt_haha,这样我们在脚本里使用txt_haha,lua就知道我们是要使用L_haha, 我们再在L_haha里调用最终的功能函数c_haha就可以了
//最终的功能函数*
void c_haha(dword a, dword b){* printf("haha--%d,%d\n",a,b); }
void c_hehe(char *str){ printf("hehe -- %s\n",str); }
//lua接口函数,里面调用我们的功能函数
static int L_haha(lua_State *L){
dword a = lua_tonumber(L,1);
dword b = lua_tonumber(L,2);
c_haha(a,b);
return 0;
}
static int L_hehe(lua_State *L){
char *str = NULL;
str = lua_tostring(L,1);
c_hehe(str);
return 0;
}
// 注册lua文件的指令所对应的函数
static const luaL_Reg txtfunctions[] = {
{"txt_haha",L_haha}, // txt_haha对应 L_haha ,而L_haha又最终调用c_haha
{"txt_hehe",L_hehe},
{ 0,0}
};
LUAMOD_API int regfunctions(lua_State *L){
luaL_newlib(L,txtfunctions); // 注册
return 1;
}
void main()
{
// 创建一个指向lua解释器的指针
lua_State *gL;
gL = luaL_newstate();
// 加载标准库
luaL_openlibs(gL);
// 参考lua源代码里面luaL_openlibs函数
luaL_requiref(gL,"xxxx",regfunctions,1); // 第二个参数名随便取,相当于一个lib名,在脚本文件里使用xxxx.txt_haha就可以了
// 现在脚本里的函数就对应上了程序里的函数 【xxxx.txt_haha -> l_haha -> c_haha】
lua_pop(gL, 1);
//加载test.txt脚本
char lbuffer[4096] ;
FILE* lf = fopen("test.txt", "rb"); // 也可以通过传递参数,指定不同的文件。我这里是把文件名写死了
long lfsize = filesize(lf);
fread(lbuffer, 1, lfsize, lf);
fclose(lf);
//把我们的测试脚本读进来
if(luaL_loadbuffer(gL, (PCHAR)lbuffer, lfsize, 0) != LUA_OK) {
printf("Lua Loadbuffer 失败\n");
lua_close(MirL);
return ;
}
lua_pcall(gL,0,0,0); //pcall loadbuffer
// 至此,函数都对应上了,脚本也加载进来了
lua_getglobal(gL,"_test1"); // 找到脚本里的 function _test1
lua_pcall(gL,0,0,0); // pcall 运行这个函数 _test1
lua_getglobal(gL,"_test2");
lua_pcall(gL,0,0,0); // pcall _test2
}
下面写一个测试脚本test.txt,里面写上
function _test1()
xxxx.txt_haha(2,3)
xxxx.txt_hehe("测试1")
end
function _test2()
xxxx.txt_haha(3,4)
xxxx.txt_hehe("测试2")
end
编译后运行程序

浙公网安备 33010602011771号