Search code examples
luaneovim

Error loading lua [string: "lua"]:1: function arguments expected near ','


I have a function in autoload\utils.lua that changes buffer based on direction:

local function GoToBuffer(count, direction)
    if count == 0 then
        if direction == "forward" then
            vim.api.nvim_command("bnext")
        elseif direction == "backward" then
            vim.api.nvim_command("bprevious")
        else
            vim.api.nvim_err_writeln("Bad argument " .. direction)
        end
        return
    end

    if vim.tbl_index(GetBufNums(), count) == -1 then
        vim.fn.nvim_notify(string.format("Invalid bufnr: %d", count), 4, { title = "nvim-config" })
        return
    end

    if direction == "forward" then
        vim.api.nvim_command(string.format("buffer%d", count))
    end
end

local function GetBufNums()
    local buf_list = {}
    for _, buf in ipairs(vim.api.nvim_get_buf_info({ buflisted = 1 })) do
        buf_list[#buf_list + 1] = buf.bufnr
    end
    return buf_list
end

I mapped a key to this function using vim.keymap.set:

local utils = require('autoload.utils')

keymap.set("n", "gb", '<cmd>:lua utils.GoToBuffer(v:count, "forward")<cr>', {})
keymap.set("n", "gB", '<cmd>:lua utils.GoToBuffer(v:count, "backward")<cr>', {})

When I use the keybind I get this error:

Error loading lua [string: "lua"]:1: function arguments expected near ','

Solution

  • The reason the code didn't work was because v:count is how you would access the variable in vimscript whereas in lua its vim.v.count