LuaLS / LuaLS/lua-language-server

Best way to implement something like an abstract base class?

Open
#2,453 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Lua
Stars
4.4k
Forks
442
PR merge metrics
No merged PRs in 30d

Description

I'm working on a framework where users of it implement a kind of module that mixes their provided logic with some optional event handlers.

Here is a simple example

-- provided by framework
---@class Base
---@field OnClick fun(self: Base, x: number, y: number)
local base = {}

---@generic T: Base
---@param name `T`
---@return T
function New(name)
	return setmetatable({}, {__index = base})
end

-- usage of framework by user

---@class MyImpl: Base
local foo = New("MyImpl")

function foo:OnClick(x, y) -- x and y are inferred as any instead of number :(
end

function foo:myHelperFunction()
end

So I expect the user to implement OnClick and fill it with their logic. My goal here is that the user automatically gets the correct types on the parameters for foo:OnClick. Here in this simple example it's just two numbers, but my real app has like > 10 such methods and some of these take complex types as parameters.

With the code above it doesn't know anything about the parameters in OnClick and shows them as any. Maybe I got something wrong with the generics, but even without all the fancy generic stuff (just @return base on New) it's the same problem.

The only work-around I found was to not use @class on the user-defined class and not define a generic, this makes the parameters on the OnCLick function definition correct! However, it now triggers injected-field on all user-defined values not defined in the base class like the myHelperFunction method :(

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the annotated Lua example from issue #2453 and inspect how the language server handles generic returns, inherited methods, and user-added fields. Done means overridden OnClick parameters are inferred as number while user-defined methods such as myHelperFunction do not produce injected-field diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
developer-experience, devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.