The two methods for callback of The Lua function by the C Module: lua and C. The interaction through the Virtual stack is simple and reliable, but the disadvantage is that C will write a little more code for Stack balancing. Today I will share with you the two methods for callback to the Lua function in the C Module. They are all cool-fried. 1. C Save the function object C module can save the objects in Lua through the registry, and then call the function when appropriate. Static int lua_callback = LUA_REFNIL; static int setnotify (lua_State * L) {lua_callback = luaL_ref (L, LUA_REGISTRYINDEX); return 0;} static int testnotify (lua_State * L) {lua_rawgeti (L, LUA_REGISTRYINDEX, lua_callback); lua_call (L, 0, 0);} luaL_ref extracts the value at the top of the stack and stores it in the specified tabel, then, an index is returned (the index of the array is visually tested ). Lua_rawgeti extracts the previously saved function object and then calls it by lua_call. Function callback () print "Callback" end cb. setnotify (callback) cb. test10000y () 2. C is easier to access the Lua global environment. C directly calls functions in Lua, just like Lua calls C. static int testenv (lua_State * L) {lua_getglobal (L, "defcallback"); lua_call (L, 0, 0);} the disadvantage of this method is that if the C Module is compiled independently, the method name is not flexible. In this method, a layer is encapsulated on the Lua end to isolate the global environment. 3. complete example cb. c # include <stdio. h> # include <stdlib. h> # include "lua. h "# include" lualib. h "# include" lauxlib. h "static int lua_callback = LUA_REFNIL; static int setnotify (lua_State * L) {lua_callback = luaL_ref (L, LUA_REGISTRYINDEX); return 0;} static int testnotify (lua_State * L) {lua_rawgeti (L, LUA_REGISTRYINDEX, lua_callback); lua_call (L, 0, 0);} static int testenv (lua_State * L) {lua_getglobal (L, "defcallback "); lua_call (L, 0, 0);} static const luaL_Reg cblib [] = {"sety y", setnotify}, {"testnotify", testnotify}, {"testenv ", testenv },{ NULL, NULL }}; int luaopen_cb (lua_State * L) {luaL_register (L, "cb", cblib); return 1;} test. lua require ("cb") function callback () print "Callback" end function defcallback () print "Predef callback" end cb. setnotify (callback) cb. testnotify () print "Done" cb. testenv ()