Tomasu / LuaGlue

C++11 Lua 5.2 Binding Library
zlib License
79 stars 22 forks source link

Callback invocation: other parameters before std::function #69

Closed ehrhart closed 10 years ago

ehrhart commented 10 years ago

When using lua callbacks, if you pass 1 or more parameters before the std::function parameter, it will return an error.

C++ code:

class Invoke
{
public:
    Invoke() {}
    ~Invoke() {}
    void workingLuaCallback(std::function<void(int)> f, int i) { printf("in c++ got %i\n", i); printf("calling std::func\n"); f(i); }
    void errorLuaCallback(int i, std::function<void(int)> f) { printf("in c++ got %i\n", i); printf("calling std::func\n"); f(i); }
};

int main()
{
    LuaGlue state

    auto &Class = this->state.Class<Invoke>("Invoke").
        ctor("new").
        method("workingLuaCallback", &Invoke::workingLuaCallback).
        method("errorLuaCallback", &Invoke::errorLuaCallback);

    this->state.open().glue();

    if(!this->state.doFile("invoke.lua"))
    {
        printf("failed to dofile: invoke.lua\n");
        printf("err: %s\n", this->state.lastError().c_str());
    }

    return 0;
}

Lua code:

function callback(i)
    io.write("in lua callback! got: "..i.."\n");
end

invoke = Invoke.new();
io.write("calling workingLuaCallback:\n");
invoke:workingLuaCallback(callback, 123);
io.write("\ncalling errorLuaCallback:\n");
invoke:errorLuaCallback(123, callback);

Result:

calling workingLuaCallback:
in c++ got 123
calling std::func
in lua callback! got: 123

calling errorLuaCallback:
failed to dofile: invoke.lua
err: invoke.lua:7: bad argument #2 to 'errorLuaCallback' (number expected, got function)
Tomasu commented 10 years ago

Have you tried the latest trunk?

ehrhart commented 10 years ago

My bad, I missed that last commit. It works now, thanks.