c++ - 如何从 C++ 向 Lua 库公开属性

标签 c++ lua

我想了解我们如何将属性公开给 lua 库。

luaL_openlib( L, kName, kVTable, 1 ); // leave "library" on top of stack

有了这个,我就可以只公开函数,因为 kVTable 指的是 luaL_Reg

typedef struct luaL_Reg {
  const char *name;
  lua_CFunction func;
} luaL_Reg;

例如:用上面的代码。我可以执行以下操作。

local myLib = require "plugin.myLib"
myLib.newFunc();

但是,我想将 Lua Table 作为 CONSTANTS 变量公开给库。

myLib.CONSTANTS.SOME_CONST_1
myLib.CONSTANTS.SOME_CONST_2

等请让我知道如何将我的库中的 lua 表公开为属性。

最佳答案

由于 luaL_openlib 将库表留在堆栈顶部,您可以使用常规 C API 向其添加新字段和子表:

luaL_openlib( L, kName, kVTable, 1 ); // leaves "library" on top of stack
lua_pushstring(L, "CONSTANTS"); 
lua_newtable(L); // this will be CONSTANTS subtable

lua_pushstring(L, "SOME_CONST_1");
lua_pushnumber(L, 42); // SOME_CONST_1 value
lua_settable(L, -3); // sets SOME_CONST_1

lua_pushstring(L, "SOME_CONST_2");
lua_pushnumber(L, 12345); // SOME_CONST_2 value
lua_settable(L, -3); // sets SOME_CONST_2

lua_settable(L, -3); // sets CONSTANTS table as field of the library table
return 1;

关于c++ - 如何从 C++ 向 Lua 库公开属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18997658/

相关文章:

c++ - float 和科学记数法

c++ - 使用 protobuf 构建 CMake 项目

c++ - 在 macOS 上安装 libsodium

ubuntu - Lua、nmap、sqlite3 和 ubuntu - 找不到模块 'luasql.sqlite3'

与多个 redis 实例交互(存储/读取)的 Lua 脚本

c++ - 如何在 Lua 5.3 中注册 C++ 类和函数

sqlite - LuaSQLite-阅读单个条目

c++ - 在 MyClass 中使用静态 std::map<int,MyClass*> 会导致无法解析的外部符号

C++:原始指针的容器

php - 在shell上执行Lua并获取内存大小和执行时间