镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

[Enhancement] Infer @operator from implementations of metamethods #2941

Closed

Description

@balt-dev

If an object's metatable implements the proper metamethods, LuaLS should be able to infer the @operator implementation.

Note that I may just be doing it wrong, as I'm using a class with a metatable of itself:

---@class Rule
---@field def fun(source: string, index: number): number, ...
T.Rule = {__metatable = false}
-- Prevent infinite recursion by not taking the shortcut of __index: table 
setmetatable(T.Rule, {
    __call = function(t, source, index) return t:parse(source, index) end,
    __index = function(t, k) if t ~= T.Rule then return T.Rule[k] end end,
    __newindex = function() error("cannot create fields on a value of type Rule") end,
    __metatable = false
})

---@param def fun(source: string, index: number): number, ...
---@return Rule
---@nodiscard
function T.Rule.new(def)
    local o = {def = def}
    setmetatable(o, T.Rule)
    return o
end

---@param other Rule
---@return Rule
---@nodiscard
function T.Rule:__add(other)
    return T.Rule.new(function(source, index)
        local succ, i = pcall(self.def, source, index)
        if not succ then error(i, 2) end

        return other.def(source, i)
    end)
end

Activity

  1. tomlau10 commented on Nov 8, 2024

    @tomlau10
    Contributor

    This has been feature requested before, but seems rejected by maintainer due to performance consideration: #599 (comment)

    However maintainer is doing a v4.0.0 rewrite, maybe it can be supported in future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions