C回调lua引用,lua回调C函数
本文根据实际代码介绍c与lua的函数调用。转载请注明出处。
c:
#include "windows.h" #include <iostream.h> extern "C"{ #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #pragma comment(lib,"lua5.1.lib") lua_State * L; static int foo (lua_State *L) { const char *buff = luaL_checkstring(L, -1); printf(buff); return 0; /* number of results */ } static int clib(lua_State *L) //给lua调用的c函数必须定义成static int XXX(lua_State *L) { const char *buff = luaL_checkstring(L, -1); //从栈顶弹出一个值 lua_pop(L, 1); //lua_pop(L, -1); //清栈 //创建索引并从栈顶弹出该对象 int ref = luaL_ref(L, LUA_REGISTRYINDEX); //根据索引取lua对象并压栈 lua_rawgeti(L, LUA_REGISTRYINDEX, ref); if (!lua_isfunction(L, -1)) { printf("call back function is not valid:%d", ref); return 0; } //压入参数 lua_pushstring(L, buff); lua_pushcfunction(L, (lua_CFunction)foo); //运行 lua_pcall(L, 2, 0,0); const char * err = luaL_checkstring(L, 1); printf("%d,err:%s/n", lua_gettop(L), err); luaL_unref(L, LUA_REGISTRYINDEX, ref); return 0; //为什么要返回1?这是有依据的,该函数把结果压入了栈,lua调用该函数将从栈中 //取1个结果 */ } static const luaL_reg lengine[] = { {"clib", clib}, {NULL, NULL}, }; int main() { //创建一个指向lua解释器的指针 L = luaL_newstate(); //加载lua标准库 luaL_openlibs(L); //注册C++函数 lua_register(L,"clib",clib); //加载脚本 luaL_register(L, "lengine", lengine); luaL_dofile(L,"1.lua"); //调用函数 // lua_getglobal(L,"run"); //运行函数并把结果压入栈 // lua_pcall(L,0,0,0); //关闭并释放资源 lua_close(L); return 0; }
lua:
local b = {} function b.a(str, cfunc) print("OK") print("lua" .. str) cfunc("this is c function/n") end lengine.clib(b.a, "test")