command.lua 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. --[[
  2. @classmod Command
  3. A Command class is used for handling different commands on the command bar.
  4. A command is composed of a target list (on which the command is executed)
  5. A command is created by returning an instance of the class Command in the form:
  6. Command( { name, {
  7. { targetA, function (arg1, ... argn)
  8. [...]
  9. end
  10. },
  11. [...]
  12. })
  13. Target "%" is used if no targets match the given one,
  14. and gives all arguments to the associated function
  15. @see export
  16. @see import
  17. ]]
  18. local lume = require(LIB_PATH.."lume")
  19. return pl.class {
  20. _name = "Command",
  21. _init = function (self, name, target_list)
  22. self.name = name
  23. self.target_list = target_list
  24. end,
  25. target_exists = function (self, target)
  26. return lume.any(self.target_list, function (v)
  27. return v[1] == target
  28. end)
  29. end,
  30. get_target_method = function (self, target)
  31. local method
  32. for k, v in ipairs(self.target_list) do
  33. if v[1] == target then method = v[2] end
  34. end
  35. return method
  36. end,
  37. suggest = function (self)
  38. return lume.reduce(lume.map(self.target_list, function (v)
  39. return v[1]
  40. end), function (v1, v2)
  41. return string.format("%s %s", v1, v2)
  42. end)
  43. end,
  44. execute = function (self, target, args)
  45. local args = args or {}
  46. if not target and not self:target_exists ("%") then return "no argument given" end
  47. if not self:target_exists (target) then
  48. if self:target_exists ("%") then
  49. return self:get_target_method ("%")(target, unpack(args))
  50. else
  51. return target .. " not found"
  52. end
  53. end
  54. return self:get_target_method (target)(unpack(args))
  55. end,
  56. }