wbthomason / packer.nvim

A use-package inspired plugin manager for Neovim. Uses native packages, supports Luarocks dependencies, written in Lua, allows for expressive config
MIT License
7.82k stars 266 forks source link

Error running config for packer.nvim: [string "..."]:0: attempt to call upvalue '' (a nil value) #1001

Closed TobTobXX closed 2 years ago

TobTobXX commented 2 years ago

Steps to reproduce

Install packer and use this init.lua:

local function nnoremap (lhs, rhs)
    vim.keymap.set('n', lhs, rhs, { noremap = true });
end

require'packer'.init();

require'packer'.use {
    'https://github.com/wbthomason/packer.nvim',
    config = function()
        nnoremap('<Leader>ps', '<cmd>PackerSync<cr>');
    end,
};

Actual behaviour

I get this error: Error running config for packer.nvim: [string "..."]:0: attempt to call upvalue '' (a nil value)

Expected behaviour

No error? The local function should be captured like any other variable.

akinsho commented 2 years ago

This is a duplicate of #351 please read through there for a solution or forward any comments there.

akinsho commented 2 years ago

https://github.com/wbthomason/packer.nvim/issues/996 has a clearer explanation/solution

TobTobXX commented 2 years ago

Thank you and sorry for duplicating.

For anyone that arrives here through a search, a TL;DR: You can't use upvalues (ie. values that get captured by an anonymous function) in the config function. Attach it to the global object and access it through there. This is actually documented in the README.

This is what worked for me:

Old:

local function nnoremap (lhs, rhs)
    vim.keymap.set('n', lhs, rhs, { noremap = true });
end

require'packer'.init();

require'packer'.use {
    'https://github.com/wbthomason/packer.nvim',
    config = function()
        nnoremap('<Leader>ps', '<cmd>PackerSync<cr>');
    end,
};

New:

local function nnoremap (lhs, rhs)
    vim.keymap.set('n', lhs, rhs, { noremap = true });
end
_G.map_fns = {
    nnoremap = nnoremap,
};

require'packer'.init();

require'packer'.use {
    'https://github.com/wbthomason/packer.nvim',
    config = function()
        map_fns.nnoremap('<Leader>ps', '<cmd>PackerSync<cr>');
    end,
};

*I'm not a Lua pro. Take it with a grain of salt.