Skip to content

Add a shortcut annotation for adding a nil,string return type to functions (@error) #3156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
piotrp opened this issue Apr 17, 2025 · 4 comments

Comments

@piotrp
Copy link

piotrp commented Apr 17, 2025

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.

@lewis6991
Copy link
Contributor

lewis6991 commented Apr 17, 2025

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.

@piotrp
Copy link
Author

piotrp commented Apr 17, 2025

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.

@lewis6991
Copy link
Contributor

lewis6991 commented Apr 17, 2025

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.

@tomlau10
Copy link
Contributor

I think you are asking for tuple return type, which has been feature requested in multiple duplicated (?) issues/discussions:


Maintainers confirmed the planned syntax for this feature (but not yet implemented of course): #3086 (comment)

---@return =(true, some_type)
---@return =(false, string)

Maybe we can see it in v4.0 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants