summaryrefslogtreecommitdiff
path: root/runtime/lua/core/commands.lua
blob: 2aa484df15ae4316f32f73f7578be4ecb3b3ba16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
local M = {}

function M.define(state, name, fn)
  state.commands[name] = fn
end

function M.bind(state, key, command_name)
  state.keymap[key] = command_name
end

function M.call(state, name, ...)
  local fn = state.commands[name]
  if not fn then
    return false, "Unknown command: " .. tostring(name)
  end

  local ok, err = pcall(fn, ...)
  if not ok then
    return false, tostring(err)
  end

  return true
end

function M.bind_fn(state, key, fn)
  if type(key) ~= "string" or key == "" then
    return false, "key must be a non-empty string"
  end
  if type(fn) ~= "function" then
    return false, "bind_fn requires a function"
  end

  local name = string.format("anon:%d", state.next_anon_command_id)
  state.next_anon_command_id = state.next_anon_command_id + 1

  state.commands[name] = fn
  state.keymap[key] = name
  return true
end

return M