Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::function and self #90

Open
joeroback opened this issue Jan 17, 2019 · 3 comments
Open

std::function and self #90

joeroback opened this issue Jan 17, 2019 · 3 comments

Comments

@joeroback
Copy link

I have a callback that get's bound in lua and from c++ I'd like to invoke that, but self is always nil and I am not sure how to access self as the lua table, not the Client* C++ object...

local client = require 'client'
local view = {}

function view:onConnect()
  self.connected = true
end

function view:create()
  client:onConnect(self.onConnect)
end
m["Client"].setClass(
    UserdataMetatable<Client>()
        .addStaticFunction("onConnect", [](Client* self, const std::function<void(void)>& connectFn)
        {
            connectFn();
        })
);

Is this possible with kaguya?

Thanks!

@joeroback
Copy link
Author

similar example...

#include <kaguya/kaguya.hpp>

#include <cstdio>

typedef void (*OnConnectFn)(void);

void somefunction(const std::function<void()>& fn)
{
    fn();
}

extern "C" int luaopen_fn(lua_State *L)
{
    kaguya::State state(L);
    kaguya::LuaTable module = state.newTable();
    module["onConnect"] = kaguya::function(somefunction);
    return module.push();
}
local fn = require 'fn'
local view = {}

function view:onConnect()
    print('onConnect', self)
end

function view:main()
    print('main', self)
    print('fn', fn)
    fn.onConnect(self.onConnect)
end

view:main()

@joeroback
Copy link
Author

I've also tried LuaFunction but no luck having self != nil

@joeroback
Copy link
Author

this hack seems to work..

#include <kaguya/kaguya.hpp>

#include <cstdio>

typedef void (*OnConnectFn)(void);

void somefunction(kaguya::LuaFunction fn, kaguya::LuaTable self)
{
    fn(self);
}

extern "C" int luaopen_fn(lua_State *L)
{
    kaguya::State state(L);
    kaguya::LuaTable module = state.newTable();
    module["onConnect"] = kaguya::function(somefunction);
    return module.push();
}
local fn = require 'fn'
local view = {}

function view:onConnect()
    print('onConnect', self)
    if self then
        print('onConnect.data', self.data)
    end
end

function view:main()
    self.data = 'foobar'
    print('main', self)
    print('fn', fn)
    fn.onConnect(view.onConnect, self)
end

view:main()
view:onConnect()

my manually passing self lua table around...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant