C代碼:
#include "windows.h"<br />#include <iostream.h> </p><p>extern "C"{<br />#include "lua.h"<br />#include "lualib.h"<br />#include "lauxlib.h"<br />} </p><p>#pragma comment(lib,"lua5.1.lib") </p><p>lua_State * L; </p><p>static int foo (lua_State *L) {<br />const char *buff = luaL_checkstring(L, -1);<br />printf(buff);<br />return 0; /* number of results */<br />}</p><p>static int clib(lua_State *L) //給lua調用的c函數必須定義成static int XXX(lua_State *L)<br />{<br /> const char *buff = luaL_checkstring(L, -1);<br /> //從棧頂彈出一個值<br /> lua_pop(L, 1);<br />//lua_pop(L, -1); //清棧 </p><p> //建立索引並從棧頂彈出該對象<br /> int ref = luaL_ref(L, LUA_REGISTRYINDEX);<br /> //根據索引取lua對象並壓棧<br /> lua_rawgeti(L, LUA_REGISTRYINDEX, ref);<br /> if (!lua_isfunction(L, -1))<br /> {<br /> printf("call back function is not valid:%d", ref);<br /> return 0;<br /> }<br /> //壓入參數<br /> lua_pushstring(L, buff);<br />lua_pushcfunction(L, (lua_CFunction)foo);</p><p> //運行<br /> lua_pcall(L, 2, 0,0);<br /> const char * err = luaL_checkstring(L, 1);<br /> printf("%d,err:%s/n", lua_gettop(L), err);<br /> luaL_unref(L, LUA_REGISTRYINDEX, ref);<br /> return 0; //為什麼要返回1?這是有依據的,該函數把結果壓入了棧,lua調用該函數將從棧中<br />//取1個結果 */<br />} </p><p>static const luaL_reg lengine[] = {<br /> {"clib", clib},<br /> {NULL, NULL},<br />}; </p><p>int main()<br />{<br />//建立一個指向lua解譯器的指標<br /> L = luaL_newstate();<br /> //載入lua標準庫<br /> luaL_openlibs(L);<br />//註冊C++函數<br /> lua_register(L,"clib",clib);<br /> //載入指令碼<br /> luaL_register(L, "lengine", lengine);<br /> luaL_dofile(L,"1.lua");<br /> //調用函數<br />// lua_getglobal(L,"run");<br />//運行函數並把結果壓入棧<br />// lua_pcall(L,0,0,0);<br /> //關閉並釋放資源<br /> lua_close(L);<br /> return 0;<br />}
lua代碼:
local b = {}<br />function b.a(str, cfunc)<br /> print("OK")<br /> print("lua" .. str)<br /> cfunc("this is c function/n")<br />end</p><p>lengine.clib(b.a, "test")<br />