Skip to content

Commit

Permalink
perf: lazy require commands
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Oct 8, 2023
1 parent 0a07fa6 commit f0cfbf9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lua/lazy/core/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,17 @@ function M.merge(...)
return ret
end

function M.lazy_require(module)

This comment has been minimized.

Copy link
@aarondill

aarondill Oct 10, 2023

This function doesn't allow functions (or any non-table value) being returned from a module.

I suggest replacing type(package.loaded[module]) == "table" with a simple non-nil check package.loaded[module]

and adding a __call method to the metatable (to make functions work):

__call = function(_, ...)
        mod = mod or require(module)
        return mod(...)
end

This comment has been minimized.

Copy link
@folke

folke Oct 10, 2023

Author Owner

This is an internal lazy module. In lazy I don't use this for function returns.

In Noice I use this, but not needed for lazy:

return function(module)
  local mod = nil

  local function load()
    if not mod then
      mod = require(module)
      package.loaded[module] = mod
    end
    return mod
  end
  -- if already loaded, return the module
  -- otherwise return a lazy module
  return type(package.loaded[module]) == "table" and package.loaded[module]
    or setmetatable({}, {
      __index = function(_, key)
        return load()[key]
      end,
      __newindex = function(_, key, value)
        load()[key] = value
      end,
      __call = function(_, ...)
        return load()(...)
      end,
    })
end
local mod = nil
-- if already loaded, return the module
-- otherwise return a lazy module
return type(package.loaded[module]) == "table" and package.loaded[module]
or setmetatable({}, {
__index = function(_, key)
mod = mod or require(module)
return mod[key]
end,
})
end

return M
1 change: 1 addition & 0 deletions lua/lazy/view/commands.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
local require = require("lazy.core.util").lazy_require
local View = require("lazy.view")
local Manage = require("lazy.manage")
local Util = require("lazy.util")
Expand Down

0 comments on commit f0cfbf9

Please sign in to comment.