lua全局表
lua的几个全局表存放在这几个索引上,前2个无法在lua脚本中直接访问,第3个等同于lua脚本的_G

mylib.c
#include <string.h> #include <stdlib.h> #include <lauxlib.h> #if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM <= 500) #define luaL_checkstring luaL_check_string #endif #ifdef __cplusplus extern "C" { #endif static int test1(lua_State* L) { printf("stack 1: %d\n", lua_gettop(L)); lua_pushstring(L, "k1"); lua_pushstring(L, "v1"); lua_rawset(L, LUA_REGISTRYINDEX); // 相当于: 栈[LUA_REGISTRYINDEX].k1 = "v1",栈顶弹出2个元素 printf("stack 2: %d\n", lua_gettop(L)); lua_pushvalue(L, LUA_REGISTRYINDEX); lua_pushvalue(L, LUA_ENVIRONINDEX); lua_pushvalue(L, LUA_GLOBALSINDEX); //对应_G printf("stack 3: %d\n", lua_gettop(L)); return 3; // 从栈弹出3个元素作为返回值 } static int PrintTop(lua_State* L) { printf("stack num: %d\n", lua_gettop(L)); return 0; } static const struct luaL_reg mylib_funcs[] = { {"test1", test1}, {"PrintTop", PrintTop}, {0, 0} }; LUALIB_API int luaopen_mylib(lua_State *L) { printf("open_mylib begin: %d\n", lua_gettop(L)); luaL_openlib(L, "mylib", mylib_funcs, 0); printf("open_mylib end: %d\n", lua_gettop(L)); return 1; //从栈弹出1个元素作为返回值 } #ifdef __cplusplus } #endif
test.lua
local function Test2() local mylib = require("mylib") local tab1, tab2, tab3 = mylib.test1() mylib.PrintTop() print(tab1, tab2, tab3) print(_G) print(tab1.k1) end Test2()
运行结果


浙公网安备 33010602011771号