notify.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. local mod_name = minetest.get_current_modname()
  2. local huds = {}
  3. local hud_timeout_seconds = 3
  4. -- defaults
  5. local position = { x = 0.1, y = 0.9}
  6. local alignment = { x = 1, y = -1}
  7. local normal_color = 0xFFFFFF
  8. local warning_color = 0xFFFF00
  9. local error_color = 0xDD0000
  10. local direction = 0
  11. local notify = {}
  12. notify.__index = notify
  13. setmetatable(notify, notify)
  14. local function hud_remove(player, playername)
  15. local hud = huds[playername]
  16. if not hud then return end
  17. if os.time() < hud_timeout_seconds + hud.time then
  18. return
  19. end
  20. player:hud_remove(hud.id)
  21. huds[playername] = nil
  22. end
  23. local function hud_create(player, message, params)
  24. local playername = player:get_player_name()
  25. local def = type(params) == "table" and params or {}
  26. def.position = def.position or position
  27. def.alignment = def.alignment or alignment
  28. def.number = def.number or def.color or normal_color
  29. def.color = nil
  30. def.position = def.position or position
  31. def.direction = def.direction or direction
  32. def.text = message or def.text
  33. def.hud_elem_type = def.hud_elem_type or "text"
  34. def.name = mod_name .. "_feedback"
  35. local id = player:hud_add(def)
  36. huds[playername] = {
  37. id = id,
  38. time = os.time(),
  39. }
  40. end
  41. notify.warn = function(player, message)
  42. notify(player, message, {color = warning_color })
  43. end
  44. notify.warning = notify.warn
  45. notify.err = function(player, message)
  46. notify(player, message, {color = error_color })
  47. end
  48. notify.error = notify.err
  49. notify.__call = function(self, player, message, params)
  50. local playername
  51. if type(player) == "string" then
  52. playername = player
  53. player = minetest.get_player_by_name(playername)
  54. elseif player and player.get_player_name then
  55. playername = player:get_player_name()
  56. else
  57. return
  58. end
  59. message = "[" .. mod_name .. "] " .. message
  60. local hud = huds[playername]
  61. if hud then
  62. player:hud_remove(hud.id)
  63. end
  64. hud_create(player, message, params)
  65. minetest.after(hud_timeout_seconds, function()
  66. hud_remove(player, playername)
  67. end)
  68. end
  69. return notify