fengari-lua / fengari

🌙 φεγγάρι - The Lua VM written in JS ES6 for Node and the browser

Home Page:https://fengari.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Creating callbacks with global functions

grilme99 opened this issue · comments

How can I execute a Lua callback from JavaScript? Heres an example code snippet.

while true do
    test(function()
        print('Hello world')
    end)
end

And here is my JavaScript code

test: (callback) => {
      testt().then(() => {
        lua_resume(L, null, 0)
        // Execute callback
      })
      return lua_yield(L, 0)
    },

I want to execute the callback after two seconds. I've already got waiting working, I just don't know how to do callbacks.

Any help with this?

Why not just waiting for test() in a coroutine?

coroutine.wrap(function() 
    while true do
        test()
        print('Hello world')
    end
end)()

Anyone will be able to execute code with what I am making. I feel like callbacks would be the best way. I need to be able to pass arguments to the callback as well.

I need to be able to pass arguments to the callback as well.

You can make test() return those arguments pushing them onto the stack before calling lua_resume:

coroutine.wrap(function() 
    while true do
        args = test()
        print(args)
    end
end)()

Also, I want to point out that your example is not a callback (in JS terminology): test() yields until its "callback" function is called, so the execution of the Lua script doesn't continue.

Anyway, I don't know how you could read a parameter of type LUA_TFUNCTION from the stack and call that Lua function later from Javascript, I don't see an obvious API for that...

Maybe you could try this way using fengari-interop's tojs (not tested, just an idea):

test: () => {
    testt().then(() => {
        var callback = fengari.interop.tojs(L, 1);
        lua_resume(L, null, 0)
        callback.invoke(/*this, [args...]*/);
    });
    return lua_yield(L, 0)
},

You should only call lua_resume from a "lua JS function" or top level. Not from a fengari-interop function.

Create your test function via fengari.lua.lua_pushjsfunction instead (and follow the Lua C API contract).

Not from a fengari-interop function.

How did you assumed he did that?

@grilme99 My replies are valid only if you create your test() function as daurnimator said.

How did you assumed he did that?

test: (callback) => {

Hi, sorry for the late reply, I've been on holiday.

@lorenzos I can't seem to be able to use Interop tojs because I don't have to JS library loaded into state because of sandboxing.

@grilme99 You don't need interop from Lua state, my code suggestion is JS, not Lua.

Yes, but for it to work, the JS library must be loaded into state. I don’t load it due to sand boxing.

@grilme99 you write the function in JS without fengari-interop. Push it into fengari with lua_pushjsfunction.