Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it Possible to Automatically Define Functions in Lua

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?

like image 709
Amarakon Avatar asked Jun 08 '26 21:06

Amarakon


1 Answers

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) :)

like image 119
kingerman88 Avatar answered Jun 10 '26 16:06

kingerman88