lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

[Feature Request] Interfaces and Implementors

Open Perodactyl opened this issue 6 months ago • 1 comments

The current class system is alright, but imagine this: I have a Stream class which is extended by ReadStream, WriteStream, SeekableStream, etc.

---@class Stream
---@field close fun() Deallocates or hangs up a stream.

---@class SeekableStream: Stream
---@field seek fun(whence: SeekWhence, offset: integer): integer

---@class ReadStream: Stream
---@field read fun(self: ReadStream, length: integer): string|nil

---@class WriteStream: Stream
---@field write fun(data: string): integer

---@class StringStream: ReadStream, SeekableStream Streams data out of a string.

Now I have a function which takes any Seekable, Readable string. How do I specify this? Either we need a conjunction type (ReadStream & SeekableStream, which has keys from both), or we need (preferably) interfaces, which are generic and can be extended by classes. The reason I suggest interfaces is because if I write this:

---@param length integer
---@return string|nil
function StringStream:read(length)
	if self.buffer == nil then
		error("Stream is closed", 2)
	end
	if self.cursor > #self.buffer then
		return nil
	end
	local out = string.sub(self.buffer, self.cursor, math.min(#self.buffer, self.cursor + length))
	self.cursor = self.cursor + #out
	return out
end

and I omit the type annotation, it assumes read is already defined because StringStream extends ReadStream, and it doesn't validate types (arguments and return type are any).

Perodactyl avatar Apr 04 '25 19:04 Perodactyl