c++ - 如何绑定(bind) C++ 公共(public)变量以在 lua 脚本中访问

标签 c++ c attributes lua bind

如何在 Lua 脚本中访问一个类中的变量。 下面是一个例子:

// C++
struct HObject{
    float x, y, z;
    float sx, sy, sz;

    void funcTest(void);
}

// Binding OBject
static bool checkFunctionArgs(lua_State* ls, const char* fname, unsigned int nargs)
{
   // etc
}

HObject* HObject_check(lua_State* ls, int index)
{
    // etc
}

static int HObject_newHObject(lua_State* ls)
{
   // etc
}

static int HObject_destructor(lua_State* ls)
{
   // etc
}

void HTest_register(lua_State* ls)
{
   // etc
}

-- Lua script
local obj = HObject:new() -- Create instance
obj:funcTest() -- OK
obj.x = 10 -- How to bind?
io.write(obj.x) -- How to bind?

我已经链接了类的函数,缺少变量。

抱歉英语...

最佳答案

你想做的事情可以通过 PIL 中描述的用户数据机制来完成,从 http://www.lua.org/pil/28.html 开始。 .你已经知道了吗?你在 obj:FuncTest() 旁边写了“Okay”,就好像你已经让那部分工作了。

我将从那个页面给出一些很好的例子。他们描述了如何创建像这样的 C 结构

typedef struct NumArray {
  int size;
  double values[1];  /* variable part */
} NumArray;

然后通过在库中注册方法

static const struct luaL_reg arraylib [] = {
  {"new", newarray},
  {"set", setarray},
  {"get", getarray},
  {"size", getsize},
  {NULL, NULL}
};

int luaopen_array (lua_State *L) {
  luaL_openlib(L, "array", arraylib, 0);
  return 1;
}

可以向用户数据添加数据和方法,并从 Lua 访问它们。下面是使用数组运算符 [],这需要做更多的工作,但他们展示了如何做。

a = array.new(1000)
a[10] = 3.4         -- setarray
print(a[10])        -- getarray   --> 3.4

现在我不是肯定的,但我想由于用户数据是一个 C 结构,它不能有函数,而只有函数指针。因此,在 C 语言中,您可能必须将“a”的适当成员传递给函数。

关于c++ - 如何绑定(bind) C++ 公共(public)变量以在 lua 脚本中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22723218/

相关文章:

c - 一种 O(n) 时间复杂度的算法,用于在数组中找到彼此之间差异最接近的一对 nos

perl - 如何更改属性类型? (珀尔哞)

c# - 从类属性获取绑定(bind)值,默认绑定(bind)属性对我不起作用!

python - 为什么不能设置类的某些属性?

c++ - 将 packaged_task 移动到 lambda

c++ - 如何在 OpenCV 中查找视频的长度?

c++ - 未指定绑定(bind)

c++ - Qt中的单元测试高度依赖(网络依赖)功能

在c中将十六进制数转换为十进制数

c - 确定输入的最大值和最小值