slider.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. local text = require "text"
  2. local slider = text:extend()
  3. slider.min_value = 0
  4. slider.max_value = 10
  5. slider.step = 1
  6. slider.value = 5
  7. slider.format = "%g"
  8. slider.editable = true
  9. slider.event_fn = function() end
  10. -- lynx.slider(event, params)
  11. -- event: function(self, menu, new_value)
  12. -- params: table
  13. --
  14. function slider:new(event, params)
  15. text.new(self, nil, params)
  16. if event then
  17. self.event_fn = event
  18. end
  19. self.selected = false
  20. self.text = self:format_fn(false)
  21. end
  22. function slider:format_fn(locked)
  23. local str = string.format(self.format, self.value)
  24. if locked then
  25. if self.value > self.min_value then
  26. str = "< " .. str
  27. end
  28. if self.value < self.max_value then
  29. str = str .. " >"
  30. end
  31. end
  32. return str
  33. end
  34. function slider:input(menu, key, state)
  35. if (not self.allow_repeat and state == "down") or state == "up" then
  36. return
  37. end
  38. if self.editable then
  39. if menu.funcs.simple_key(key) == "enter" and state == "pressed" then
  40. self.selected = not self.selected
  41. menu.locked = self.selected
  42. self.text = self:format_fn(self.selected)
  43. elseif self.selected then
  44. if menu.funcs.simple_key(key) == "left" then
  45. self.value = math.max(self.min_value, self.value - self.step)
  46. self:event_fn(menu, self.value)
  47. self.text = self:format_fn(self.selected)
  48. elseif menu.funcs.simple_key(key) == "right" then
  49. self.value = math.min(self.max_value, self.value + self.step)
  50. self:event_fn(menu, self.value)
  51. self.text = self:format_fn(self.selected)
  52. end
  53. end
  54. end
  55. end
  56. function slider:mouse(menu, x, y, btn)
  57. if btn == 1 then
  58. self:input(menu, "enter", "pressed")
  59. end
  60. end
  61. function slider:__tostring()
  62. return "lynx.slider"
  63. end
  64. return slider