Add a shortcut annotation for adding a `nil,string` return type to functions (`@error`)
Returning of errors from Lua functions is often done by returning nil + error message (nil,string):
---@return table
---@overload fun(): nil, string
local function doSomething()
but this syntax can get complex when function takes parameters, or has other overloads. An old solution from LDoc was to use a @error annotation - I propose to add something similar to LuaLS.
In LuaLS (or emmylua_ls) that overload doesn't mean anything since it is indistinguishable from the regular signature.
It should just be:
--- @return table? result
--- @return string? err
local function doSomething() end
LDoc was only every used for documentation, so the signatures never had to make sense from a type system POV.
Then what about this output from VSCode with LuaLS / IDEA with EmmyLua2?
My example is typed in both LS implementations as two separate signatures:
function doSomething()
-> table
function doSomething()
-> nil
2. string
so it gives static analysis a chance to choose one of these two types when typing results.
Yours results in a single ambiguous result:
function doSomething2()
-> result: table?
2. err: string?
According to this nil, nil is a possible outcome.
In practice, regardless of how you specify it, nil, nil will be a valid outcome as each variable is analysed independently.
They can only be distinguished if each prototype has different arguments, then the tool can choose one.
I think you are asking for tuple return type, which has been feature requested in multiple duplicated (?) issues/discussions:
- https://github.com/LuaLS/lua-language-server/issues/1583
- https://github.com/LuaLS/lua-language-server/issues/2933
- https://github.com/LuaLS/lua-language-server/issues/3078
- https://github.com/LuaLS/lua-language-server/discussions/3102
Maintainers confirmed the planned syntax for this feature (but not yet implemented of course): https://github.com/LuaLS/lua-language-server/discussions/3086#discussioncomment-12295458
---@return =(true, some_type)
---@return =(false, string)
Maybe we can see it in v4.0 🙂