My observer breaks on startup.... Why?

Once I reach the setlement location screen, I get this error for my observer:

develop-2807 (x64)
bastioneers/ai/observers/armor_battery_observer.lua:52: attempt to index field '_on_battery' (a function value)
stack traceback:
	[C]: ?
	bastioneers/ai/observers/armor_battery_observer.lua:52: in function <bastioneers/ai/observers/armor_battery_observer.lua:50>
	[C]: in function 'destroy'
	...ehearth/components/observers/observers_component.lua:74: in function 'remove_observer'
	stonehearth/services/server/ai/ai_injector.lua:76: in function 'destroy'
	stonehearth/components/ai/ai_component.lua:99: in function <stonehearth/components/ai/ai_component.lua:97>
	[C]: in function 'destroy_entity'
	radiant/modules/entities.lua:82: in function 'destroy_entity'
	...vices/server/game_creation/game_creation_service.lua:66: in function <...vices/server/game_creation/game_creation_service.lua:60>

The observer .lua in question:

local ArmorBatteryObserver = class()
--Called first every time
function ArmorBatteryObserver:initialize()
	-- list all the saved variables
	self._sv.entity = nil
end
--Called once on creation
function ArmorBatteryObserver:create(entity)
	self._sv.entity = entity
end
--Always called. If restore, called after restore.
function ArmorBatteryObserver:activate()
	self._entity = self._sv.entity
end
function ArmorBatteryObserver:post_activate()
  self._battery_listener = radiant.events.listen(self._entity, 'stonehearth:combat:battery', self, self._on_battery)
end
function ArmorBatteryObserver:_on_battery(e)
	-- Get the entity's armor data
  local armor = radiant.entities.get_equipped_item(self._entity, 'torso')
  -- Check the armor's data
  if not armor then
        -- Leave if no armor exists
    return
  end
    -- Get the armor's brittleness component
    local brittle_component = armor:get_component('bastioneers:brittleness')
    -- Check if it is brittle
  	if not brittle_component then
      -- leave if no brittle data exists
    	return
  	end
    brittle_component:reduce_current_durability()
    if brittle_component:get_current_durability() <= 0 then
      radiant.entities.unequip_item (self._entity, armor)
    end
end
function ArmorBatteryObserver:destroy()
  	if self._on_battery then
  	   self._on_battery:destroy()
  	   self._on_battery = nil
  	end
end
function ArmorBatteryObserver:entity()
  return self._entity
end
return ArmorBatteryObserver

It appears to be related to the destroy function. This issue leaves me clueless… Any help is highly appreciated!

It also seems to happen when my hearthlings die, so it might be an issue with the destroy method…

I think you want to destroy the battery listener, not self._on_battery itself. on_battery is the name of a function, and that function cannot be destroyed.
you probably want

if self._battery_listener then
self._battery_listener:destroy()
self._battery_listener = nil
end

3 Likes