Silverlan
Silverlan

Reputation: 2911

lua / luabind - Add and overwrite class methods through lua

I'm using lua 5.2.2 with luabind 0.9.

I'd like to be able to add additional class-methods through lua for any classes that I've bound in c++, but I'm unsure how to do it.

The problem is that luabind uses a function as the __index-metamethod for any bound classes instead of a table, so I don't see a way to access the class-methods at all.

e.g., I'm binding my classes like this:

luabind::module(lua)
[
    luabind::class_<testClass>("TestClass")
    .def(luabind::constructor<>())
    .def("TestFunc",&TestFunc)
];

What I essentially want to do is to add a lua-function to the list of methods for this class, and be able to overwrite existing ones:

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

Any help would be appreciated.

Upvotes: 1

Views: 614

Answers (1)

Little Coding Fox
Little Coding Fox

Reputation: 217

You could use a luabind::object property and register it with the .property method of luabind

Something like this:

//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)

Then you just need to call the luabind::object according to the luabind docs.

It's not exactly what you want to do but it could help you overwrite the function I think. You could bind the real function and have a property, check if the luabind::object is non-null, and call it or the native function.

Upvotes: 0

Related Questions