xiangnanscu / js2lua

js2lua Writing LuaJIT with the expressiveness of JavaScript.
https://xiangnanscu.github.io/js2lua/
3 stars 0 forks source link

Question: how to deal with functions that return multiple values #5

Closed al1-ce closed 1 month ago

al1-ce commented 1 month ago

Assume lua code:

local ok, ret = pcall(func, "something")

How would I translate it with js2lua?

xiangnanscu commented 1 month ago

I don't get it. This repo is about JS to lua, so JS will always return a single value for lua.

al1-ce commented 1 month ago

True, but I'm asking about how to deal in js with lua functions that return multiple values like pcall

I tried

let [ok, ret] = pcall(require, "somemod");

But it was generating something like

local ok, ret;
local __tmp = pcall(require, "somemod")
ok = __tmp[1]
ret = __tmp[2]

Which would produce errors since __tmp is not an array

I did found quick and dirty solution to that

function pack2(a, b) {
    return [a, b];
}

let status = pack2(pcall(require, "somemod"))

But it is indeed quick and dirty and it'd be preferable to have some sort of way to do it natively

xiangnanscu commented 1 month ago

I get it. On one hand, we would like to get local ok, ret = foo() from let [ok, ret] = foo() if foo is a common Lua function that returns multiple values (like pcall, xpcall, etc.). On the other hand, we might also want let [e1, e2, e3] = foo() to be processed in the current way if foo is a user-defined function that returns an array. Given this repo's slogan, "Writing LuaJIT with the expressiveness of JavaScript," functions like pcall should be specially handled, while other functions will be handled as usual. So JS code:

let [ok, ret] = pcall()
let [e1, e2] = my_func()

Will be:

local ok, ret = pcall()
local e1, e2
do
    local __tmp = my_func()
    e1 = __tmp[1]
    e2 = __tmp[2]
end

What's your opinion?

al1-ce commented 1 month ago

I've rarely seen non-std lua functions return multiple values so this is a good solution imo

xiangnanscu commented 1 month ago

258cbcc3f368e9f827100bc95e1fef773e9d93ed