satoren / kaguya

C++ binding to Lua
Boost Software License 1.0
345 stars 70 forks source link

Is it possible add __call meta method? #38

Closed aster2013 closed 8 years ago

aster2013 commented 8 years ago

for example:

class Vector3
{
public:
    Vector3(float x, float y, float z);
};

It can call

local vec = Vector3.new(1, 2, 3)

to create a vector3 object. but sometimes I want to create the user data with

local vec = Vector3(1, 2, 3)
```, 

Is possible add ```__call``` method for class?
satoren commented 8 years ago

Can it but a little troublesome.

    state["Vector3"].setClass(kaguya::UserdataMetatable<Vector3>()
        .setConstructors<ABC(float,float,float)>()
    );

    kaguya::LuaTable call_con_table = state.newTable();
    call_con_table["__call"] = kaguya::LuaCodeChunkResult("return function(t,...) return t.new(...) end");
    state["Vector3"].setMetatable(call_con_table);

If you want set to multiple metatable, only need one call_con_table.

aster2013 commented 8 years ago

Add a fucntion to TableKeyReference::setCallable() So it can change to

state["Vector3"].setClass(kaguya::UserdataMetatable<Vector3>()
        .setConstructors<ABC(float,float,float)>()
    );

state["Vector3"].setCallable();
satoren commented 8 years ago

How about this?

state["Vector3"].setClass(kaguya::UserdataMetatable<Vector3>()
        .setConstructors<Vector3(float,float,float)>()
        .enableCallConstruct()
    );
aster2013 commented 8 years ago

Cool!

aster2013 commented 8 years ago
class Base
{
    ... 
};

class Derived : public Base
{
    ... 
};

state["Derived"].setClass(kaguya::UserdataMetatable<Derived>()
        .setConstructors< ... >()
        .enableCallConstruct()
    );

Please note: When set the callable metatable to Derived class, please make it also call Base member functions.

Thanks, you are so nice.

satoren commented 8 years ago

Or

state["Vector3"].setClass(kaguya::UserdataMetatable<Vector3>()
        .setConstructors<Vector3(float,float,float)>(true)
    );

But this is true for what don't know at first look.

aster2013 commented 8 years ago

or make callable is always enabled in kaguya.

satoren commented 8 years ago

It adopted. Leave new , because for compatibility and __call has extra cost.