Home > Software design >  lua: dynamic function creation inside a loop
lua: dynamic function creation inside a loop

Time:08-31

I have a mappings.lua file, in which i am creating functions like this:

local km = vim.api.nvim_set_keymap
local op = { noremap = true, silent = true }

local n = function(lhs, rhs)                                                                                                          
    return km('n', lhs, rhs, op)
end

local v = function(lhs, rhs)
    return km('v', lhs, rhs, op)
end

local t = function(lhs, rhs)
    return km('t', lhs, rhs, op)
end

local i = function(lhs, rhs)
    return km('i', lhs, rhs, op)
end

that allows me to create mappings easily like this:

v('kj', '<esc>')

n('<a-h>', '<c-w>h')
n('<a-j>', '<c-w>j')
n('<a-k>', '<c-w>k')
n('<a-l>', '<c-w>l')

how to create the functions easily using for loops

my attempts using loadstring did not work:

for k, v in pairs({'n','v','t','i','x'}) do
    loadstring("local function "..v.."(lhs,rhs) return km("..v..", lhs, rhs, op) end")
end

CodePudding user response:

local km = vim.api.nvim_set_keymap
local op = { noremap = true, silent = true }
  
local map = {}
local keys = {"n", "v", "t", "i", "x"}

for i, v in ipairs(keys) do
  map[v] = function (lhs, rhs)
      return km(v, lhs, rhs, op)
    end
end

Then you can do this

map.v('kj', '<esc>')

map.n('<a-h>', '<c-w>h')

Or if you need a local alias

local n = map.n
n('<a-h>', '<c-w>h')

Although I'm not sure why if the effort is worth it.

I'd probably use

function map(x, lhs, rhs)
  return km(x, lhs, rhs, op)
end

map("v", "kj", "<esc>")

or just stick with the km function. But that's personal preference.

  • Related