--excerpt from royal's undying runner code, customized to work for buildings with the help of seelpit.

util.PrintToChatAll("Script active!")

ents.AddCreateCallback("obj_dispenser", function(entity, classname)
	timer.Simple(0, function()
		if not IsValid(entity) then
			return
		end
		local name = entity:GetName()
		util.PrintToChatAll("Dispenser name: "..name)
		UndyingBuildingSpawn(entity)
	end)
end)

function ShowName(ent)
    if not IsValid(ent) then
		return
	end
	local dispName = ent:GetName()
    util.PrintToChatAll("Entity name checked and it's: "..dispName)
	return (dispName == "testdisp")
end

function UndyingBuildingSpawn(activator)
	local dispName = ShowName(activator) --returns false if it doesn't match
	if not dispName then
		util.PrintToChatAll("Cringe, not testdisp!")
		return
	end
	
	activator:AddCallback(ON_DAMAGE_RECEIVED_PRE, function(_, damageInfo)
		-- just in case
		if not activator:IsAlive() then
			return
		end
		-- ShowName(activator)
		local curHealth = activator.m_iHealth
		
		local damage = damageInfo.Damage
		--buildings can't get crit
		-- if (damageInfo.DamageType & DMG_CRITICAL > 0) then 
			-- damage = damageInfo.Damage * 3.1
		-- end
		
		util.PrintToChatAll("Damage to be dealt: "..tostring(damage))
		
		--If the incoming damage is lethal, set our health to 1 instead. Make ourselves invincible at 1000 health
		if curHealth - (damage + 1) <= 0 and curHealth ~= 1 then
			damageInfo.Damage = 0
			damageInfo.DamageType = DMG_GENERIC

			-- set health to 1
			local setHealthDmgInfo = {
				Attacker = damageInfo.Attacker,
				Inflictor = damageInfo.Inflictor,
				Weapon = damageInfo.Weapon,
				Damage = curHealth - 2,
				CritType = 0,
				DamageType = damageInfo.DamageType,
				DamageCustom = damageInfo.DamageCustom,
				DamagePosition = damageInfo.DamagePosition,
				DamageForce = damageInfo.DamageForce,
				ReportedPosition = damageInfo.ReportedPosition,
			}
			util.PrintToChatAll("Damage actually dealt: "..tostring(damage))
			activator:TakeDamage(setHealthDmgInfo)

			return true
		end
		
		return true
	end)
end