【问题标题】:lua / luabind - Add and overwrite class methods through lualua / luabind - 通过 lua 添加和覆盖类方法
【发布时间】:2013-10-08 21:22:39
【问题描述】:

我正在使用 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

任何帮助将不胜感激。

【问题讨论】:

    标签: indexing lua meta luabind


    【解决方案1】:

    您可以使用 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 是否为非空,然后调用它或本地函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-30
      • 2011-03-05
      • 2012-07-21
      • 2014-08-05
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      相关资源
      最近更新 更多