Skip to content
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

[Feature request] Add a pseudo-type for custom require-like functions #3003

Open
SkyyySi opened this issue Dec 22, 2024 · 0 comments
Open

[Feature request] Add a pseudo-type for custom require-like functions #3003

SkyyySi opened this issue Dec 22, 2024 · 0 comments

Comments

@SkyyySi
Copy link

SkyyySi commented Dec 22, 2024

I think it would be useful to have something like a Require<T>-type. This type would take a literal string type T and evaluate as the same type that calling require(modname: T) would. This way, a wrapper around require could easily be built like this:

--- Require a module, throwing an error if it returned `true` (meaning that you
--- probably forgot to actually return something from it).
---@generic T : string
---@param module_name T
---@return Require<T> module -- <-- Note the use of `Require<T>`
local function checked_require(module_name)
    assert(type(module_name) == "string", "The `module_name` must be a string!")

    local module = require(module_name)

    assert(
        module ~= true,
        string.format(
            "Could not import module: `require(%q)` returned `true`!",
            module_name
        )
    )

    return module
end

--------------------------------------------------------------------------------

local socket = checked_require("socket")
local socket_require = require("socket")

assert(socket == socket_require)

The type-hint of require() could then be changed to the following:

---@generic T : string
---@param module_name T
---@return Require<T> module
function require(module_name) end

The language server already has a way to make global functions behave like require built-in, in the form of the "Lua.runtime.special" setting. This type would essentially do the same, except that it would be more powerful / broadly usable, since it could be applied to any variable. It would also be easier to use, since it's just another type in your code instead of something hiding in a config file.

@SkyyySi SkyyySi changed the title [Feature request] A pseudo-type for custom require-like functions [Feature request] Add a pseudo-type for custom require-like functions Dec 22, 2024
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

1 participant