首先封装一个类lua_wrapper,供需要向lua暴露接口的c++类继承: extern "C" { #include <lua.h> #include <lua.hpp> #include <lauxlib.h> #include <luaconf.h> #include <lualib.h> } class lua_wrapper { typedef int (*fun_cpp_api)(lua_State* luaState); private: static lua_State *s_lua_ptr; map<string, fun_cpp_api> m_map_api; public: static bool lua_base_init() { if (s_lua_ptr = NULL) { s_lua_ptr = lua_open(); if (s_lua_ptr != NULL) { luaopen_base(s_lua_ptr); luaopen_table(s_lua_ptr); luaopen_string(s_lua_ptr); luaopen_math(s_lua_ptr); return true; } } return false; } int Call(const string fun_name, lua_State* luaState) { map<string, fun_cpp_api>::const_iterator iter = m_map_api.find(fun_name); if (iter == m_map_api.end()) { return -1; } return (iter->second)(luaState); } #define API_ADD_FUN(fun) do { / m_map_api[#fun] = fun; / setfield(#fun, fun); / } while(0) #define BEGIN_FUNCTION_MAP(x) / lua_newtable(s_lua_ptr); / API_ADD_FUN(Call); / API_ADD_FUN(AttachListener); / API_ADD_FUN(DetachListener); }; 详细说明: 。。。