observers.lua 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. local function player_names_excluding(exclude_player_name)
  2. local player_names = {}
  3. for _, player in ipairs(core.get_connected_players()) do
  4. player_names[player:get_player_name()] = true
  5. end
  6. player_names[exclude_player_name] = nil
  7. return player_names
  8. end
  9. core.register_entity("testentities:observable", {
  10. initial_properties = {
  11. visual = "sprite",
  12. textures = { "testentities_sprite.png" },
  13. static_save = false,
  14. infotext = "Punch to set observers to anyone but you"
  15. },
  16. on_activate = function(self)
  17. self.object:set_armor_groups({punch_operable = 1})
  18. assert(self.object:get_observers() == nil)
  19. -- Using a value of `false` in the table should error.
  20. assert(not pcall(self.object, self.object.set_observers, self.object, {test = false}))
  21. end,
  22. on_punch = function(self, puncher)
  23. local puncher_name = puncher:get_player_name()
  24. local observers = player_names_excluding(puncher_name)
  25. self.object:set_observers(observers)
  26. local got_observers = self.object:get_observers()
  27. for name in pairs(observers) do
  28. assert(got_observers[name])
  29. end
  30. for name in pairs(got_observers) do
  31. assert(observers[name])
  32. end
  33. self.object:set_properties({infotext = "Excluding " .. puncher_name})
  34. return true
  35. end
  36. })