Home > Software design >  Is it Possible to Automatically Define Functions in Lua
Is it Possible to Automatically Define Functions in Lua

Time:09-08

These are some functions I want to define:

local function nmap(lhs, rhs, opts)
    keymap.set("n", lhs, rhs, opts)
end

local function imap(lhs, rhs, opts)
    keymap.set("i", lhs, rhs, opts)
end

local function vmap(lhs, rhs, opts)
    keymap.set("v", lhs, rhs, opts)
end

local function cmap(lhs, rhs, opts)
    keymap.set("c", lhs, rhs, opts)
end

local function omap(lhs, rhs, opts)
    keymap.set("o", lhs, rhs, opts)
end

It is repetitive though. Is there a more efficient way to define these functions? The only thing that is different in each of these functions is one letter (n, i, v, c, o). Can I use a for loop to automatically define each one?

CodePudding user response:

Using _G (the global environment table) you can do that.

local letters = {'n', 'i', 'v', 'c', 'o'}

for _, c in ipairs(letters) do
    _G[c..'map'] = function(...)
        keymap.set(c, ...)
    end
end

-- cmap(insert, arguments, here)

This is actually stated under this guide as well https://github.com/nanotee/nvim-lua-guide See the The vim namespace section


Just be careful not to override any important variables (like the table or math library haha) :)

  • Related