daurnimator / lua.vm.js

The project is superceded by Fengari. See https://fengari.io/
MIT License
836 stars 101 forks source link

multiple returns form js #54

Closed salt42 closed 8 years ago

salt42 commented 8 years ago

Is it possible to return multiple values from javascript to lua?

daurnimator commented 8 years ago

Use an array?

Are you calling into lua from js or calling into js from lua?

salt42 commented 8 years ago

i calling from lua to js.

daurnimator commented 8 years ago

i calling from lua to js.

Javascript functions only return a single value. Where are the multiple values?

salt42 commented 8 years ago

what i mean is calling local a, b = js.global.testFunc() in lua.

daurnimator commented 8 years ago

what i mean is local a, b = js.global.testFunc()

Javascript functions only return a single value.

Try this in javascript and you'll see.

console.log((function () {return 1,2})())
salt42 commented 8 years ago

yes i know that i can't do this in JS. Therefore, I want to do it more like this:

       test() {
            L.pushstring("val1");
            L.pushstring("val2");
            return 2;
        }
daurnimator commented 8 years ago

You can; but it's a bit ugly, as you have to register your javascript function as a C function in emscripten. Emscripten also has limited runtime function slots.

That would look like:

L.pushcclosure(emscripten.Runtime.addFunction(function(L){
    L = new Lua.State(L);
    L.pushstring("val1");
    L.pushstring("val2");
    return 2;
}, 0)

Then you'd need to export that cclosure to lua.

Much easier to just use an array and unpack.

function test() {
    return ["val1", "val2"]
}
local function test()
   local r = real_test()
   return r[0], r[1]
end

Sadly you can't use table.unpack for this in 5.2. Once I upgrade lua.vm.js to 5.3 you'll just be able to call table.unpack(js.global.test(),0) if it returns an array.

salt42 commented 8 years ago

i hoped that i can avoid to wrap everything. :/ thx for the quick help! and great project.