vvkatwss vvkatwss
vvkatwss vvkatwss

Reputation: 3569

Call c function from Lua-lanes

I want to call c function from lua using lanes.

int initApp(lua_State *L) {
    lua_createtable(L, 0, 0);
    
    lua_pushcfunction(L, get_appinfo);
    lua_setfield(L, -2, "get_appinfo");
    
    lua_setglobal(L, "App");
    
    return 0;
}
local function thread1(n)
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    package.preload['App'] = function() return App end
    package.loaded['App'] = App
    local app = require 'App'
    print(app, app.get_appinfo) --table: 0x1234    function: 0x5678
    --(1)
    f = lanes.gen('*', {required = {'App'}}, thread1) --Lua Error: module 'App' not found: no field package.preload['App']...
    --(2)
    --f = lanes.gen('App', thread1) -- Bad library name: App
    a = f(1)
    sleep(1)
end

When I run variant (1), I get Lua Error: module 'App' not found: no field package.preload['App']...no file '/App.lua'.... When I run variant (2), I get Bad library name: App.

How to call App.get_appinfo() using lanes? I can move all App functions into package, but it must be loaded from memory, not filesystem. I embed all lua packages.

Upvotes: 1

Views: 111

Answers (2)

vvkatwss vvkatwss
vvkatwss vvkatwss

Reputation: 3569

To call c function, I must pass a function for on_state_create to lanes.configure.

//c code
int init_App(lua_State *L) {
    lua_createtable(L, 0, 0);
    
    lua_pushcfunction(L, get_appinfo);
    lua_setfield(L, -2, "get_appinfo");
    
    lua_setglobal(L, "App");
    
    return 0;
}

int init(lua_State *L) {
    lua_pushcfunction(L, init_App);
    lua_setglobal(L, "init_App");
    luaL_dostring(L, "local lanes = require 'lanes'.configure{on_state_create=init_App}; local l = lanes.linda()");
    luaL_dostring(L, "startlanes()");
}

--lua code
local function thread1(n)
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    local f = lanes.gen('*', thread1)
    a = f(1)
    sleep(1)
    print(a[1])
end

Upvotes: 0

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23737

  1. Expose your C function initApp to Lua, for example, as _G.init_App
    lua_pushcfunction(L, initApp);
    lua_setglobal(L, "init_App");
  1. Pass it as a parameter when starting each lane
  2. Inside a lane, invoke init_App (received as the second parameter) - it will create your library
local function thread1(n, init_App)
    init_App()  -- create global table App in the current lane
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    local f = lanes.gen('*', thread1)
    a = f(1, init_App)  -- pass your module loader as argument
    sleep(1)
end

Upvotes: 0

Related Questions