我正在使用 lua 5.2.2 和 luabind 0.9。
我希望能够通过 lua 为我在 C++ 中绑定的任何类添加额外的类方法,但我不确定如何做到这一点。
问题是 luabind 使用函数作为任何绑定类的 __index-metamethod,而不是表,所以我根本看不到访问类方法的方法。
例如,我像这样绑定我的类:
luabind::module(lua)
[
luabind::class_<testClass>("TestClass")
.def(luabind::constructor<>())
.def("TestFunc",&TestFunc)
];
我本质上想做的是将 lua 函数添加到此类的方法列表中,并能够覆盖现有的方法:
local t = tableOfClassMethods
local r = t.TestFunc -- Reference to the c++-function we've bound
t.SomeFunction = function(o) end -- New function for all objects of this class
t.TestFunc = function(o) end -- Should overwrite the c++-function of the same name
如有任何帮助,我们将不胜感激。
您可以使用 luabind::object 属性并使用 luabind 的 .property 方法注册它
类似这样的:
//Class
class FunctionCaller
{
public:
luabind::object Fn;
void SetFn(luabind::object NewFn)
{
Fn = NewFn;
};
luabind::object GetFn()
{
return Fn;
};
};
//Binding Code
luabind::class_<FunctionCaller>("FunctionCaller")
.def(luabind::constructor<>())
.property("Fn", &FunctionCaller::Fn, &FunctionCaller::SetFn, &FunctionCaller::GetFn)
然后你只需要根据 luabind 文档调用 luabind::object 即可。
这并不完全是您想要做的,但它可以帮助您覆盖我认为的函数。您可以绑定真实函数并拥有一个属性,检查 luabind::object 是否非空,然后调用它或本机函数。