通过require的方式可以加载动态库,然后脚本就可以使用库中提供的函数,一般过程如下:
比如有一个动态库名为:MyFirstLua.dll
则使用时:MyFirstLua = require("MyFirstLua")
导出的函数接口名称一定是 int luaopen_XXXX(lua_State* L)格式,且XXXX一定是导出库的文件名
#ifdef __cplusplus
extern "C" {
#endif#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"#ifdef __cplusplus
}
#endif#pragma comment(lib, "liblua.lib")static int export_add(lua_State *L) {if (lua_isinteger(L, 1) && lua_isinteger(L,2)) {lua_Integer n = lua_tointeger(L, 1);lua_Integer n2 = lua_tointeger(L, 2);lua_pushinteger(L, n+n2);}elselua_pushnil(L);return 1;
}static int export_print(lua_State* L)
{return 0;
}static const luaL_Reg exportLib[] = {{"add",export_add},{"print",export_print},{NULL, NULL}
};#ifdef __cplusplus
extern "C" {
#endif__declspec(dllexport) int luaopen_MyFirstLua(lua_State* L){luaL_newlib(L, exportLib);return 1;}#ifdef __cplusplus
}
#endif
上述代码导出一个MyFirstLua的dll库,并且导出luaopen_MyFirstLua函数接口。
在该函数中通过luaL_newlib的方式将函数注册导出到MyFirstLua表对象中。
通常导出函数形如:static int export_myfunction(lua_State* L),它的返回值代表这这个导出函数在脚本中应该返回多少个值。