Search code examples
lualua-lanes

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.


Solution

  • 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