PlutoLang / Pluto

A superset of Lua 5.4 with a focus on general-purpose programming.
https://pluto-lang.org/docs/Introduction
MIT License
338 stars 20 forks source link

Exports return at block end #825

Closed XmiliaH closed 2 months ago

XmiliaH commented 2 months ago

Is it intended that exports in a block will cause a return when the block ends?

Looking at

local function f(extended)
    export function r1() end
    if extended then
        export function r2() end
    end
end

local t = f(true)
print(t.r1, t.r2)

I would expect a table with both, r1 and r2 to be returned but only r2 is in the table as the if block creates a new export scope and will return at the end of the if since there was an export in the body.

Sainan commented 2 months ago

Yes, this is the documented behavior. The return statement is implied at the end of the block. It is mainly intended for top-level functions, but it's also useful in function bodies to push into package.preloaded.

XmiliaH commented 2 months ago

The documentation only states

The return statement is automatically generated.

not if this happens at the end of the function or the end of a block (end of if, end of loop, end of switch).

So it does not state how my example is translated.

local function f(extended)
    local function r1() end
    if extended then
        local function r2() end
        return {r2=r2}
    end
    return {r1=r1}
end

or

local function f(extended)
    local function r1() end
    if extended then
        local function r2() end
        return {r1=r1, r2=r2}
    end
    return {r1=r1}
end

or

local function f(extended)
    local exports = {}
    local function r1() end
    exports.r1 = r1
    if extended then
        local function r2() end
        exports.r2 = r2
    end
    return exports
end
Sainan commented 2 months ago

Well, it does have the example:

-- end of scope; 'return' is automatically generated

Maybe can be a bit more explicit.