observer.lua 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. local text = require "text"
  2. local observer = text:extend()
  3. observer.raw = false
  4. observer.format = "%s: %s"
  5. observer.continous = true
  6. -- lynx.observer(variable, key, format, params)
  7. -- variable: table
  8. -- key: any
  9. -- format: string (by default, format_fn uses string.format with key and value)
  10. -- params: table
  11. --
  12. function observer:new(variable, key, format, params)
  13. text.new(self, nil, params)
  14. self.variable = variable or {}
  15. self.key = key
  16. self.format = format
  17. self.value = variable[key]
  18. self.text = self:format_fn()
  19. end
  20. function observer:format_fn()
  21. return string.format(self.format, self.key, self.value)
  22. end
  23. function observer:update(menu, dt)
  24. self.super.update(self, menu, dt)
  25. if not self.selected or self.continous then -- allow merging with editors
  26. local var = self.variable
  27. local value = self.raw and rawget(var, self.key) or var[self.key]
  28. if self.value ~= value then
  29. self.value = value
  30. self.text = self:format_fn(self.selected)
  31. end
  32. end
  33. end
  34. function observer:__tostring()
  35. return "lynx.observer"
  36. end
  37. return observer