Pinkstack/roblox-luau-corpus-text huggingface dataset:
--[[Engine]]


	--Torque Curve
	Tune.Horsepower		= 100		--	[TORQUE CURVE VISUAL]
	Tune.IdleRPM		= 700		--		https://www.desmos.com/calculator/2uo3hqwdhf
	Tune.PeakRPM		= 6000		--		Use sliders to manipulate values
	Tune.Redline		= 6700		--		Copy and paste slider values into the respective tune values
	Tune.EqPoint		= 5500
	Tune.PeakSharpness	= 7.5
	Tune.CurveMult		= 0.20
	
	--Incline Compensation
	Tune.InclineComp	= 1.7			-- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
	
	--Misc
	Tune.RevAccel		= 150		-- RPM acceleration when clutch is off
	Tune.RevDecay		= 75		-- RPM decay when clutch is off
	Tune.RevBounce		= 500		-- RPM kickback from redline
	Tune.IdleThrottle	= 3			-- Percent throttle at idle
	Tune.ClutchTol		= 500		-- Clutch engagement threshold (higher = faster response)
-- Value specific waypoint methods



do
	function Waypoints.fromVector3(... : Vector3) : Waypoints
		local args = {...}
		local waypoints = {}
		for i = 1, #args do
			assert(typeof(args[i]) == "Vector3", tostring(args[i]) .. "is not a Vector3 value.")
			table.insert(waypoints, args[i])
		end
		return waypoints
	end

	function Waypoints.fromCFrame(...) : Waypoints
		local args = {...}
		local waypoints = {}
		for i = 1, #args do
			assert(typeof(args[i]) == "CFrame", args[i] .. "is not a CFrame value.")
			table.insert(waypoints, args[i].Position)
		end
		return waypoints
	end

	function Waypoints.fromInstance(...) : Waypoints
		local args = {...}
		local waypoints = {}
		for i = 1, #args do
			assert(typeof(args[i]) == "Instance", args[i].Name .. "is not an Instance.")
			assert(args[i]:IsA("BasePart"), args[i].Name .. "is not a BasePart.")
			table.insert(waypoints, args[i].Position)
		end
		return waypoints
	end
end


local waypointTypes = {
	Vector3 = Waypoints.fromVector3,
	CFrame = Waypoints.fromCFrame,
	Instance = Waypoints.fromInstance
}

function Waypoints.new(... : Vector3 | CFrame | Instance) : Waypoints -- Creates waypoints
	assert(waypointTypes[typeof(...)], 
		"Parameters are not correct value types, try using value specific functions.")
	return waypointTypes[typeof(...)](...)
end



return Waypoints
--[=[
	@within RemoteSignal
	@interface Connection
	.Disconnect () -> nil
]=]



function RemoteSignal.new(parent: Instance, name: string, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware?)
	local self = setmetatable({}, RemoteSignal)
	self._re = Instance.new("RemoteEvent")
	self._re.Name = name
	self._re.Parent = parent
	if outboundMiddleware and #outboundMiddleware > 0 then
		self._hasOutbound = true
		self._outbound = outboundMiddleware
	else
		self._hasOutbound = false
	end
	if inboundMiddleware and #inboundMiddleware > 0 then
		self._directConnect = false
		self._signal = Signal.new()
		self._re.OnServerEvent:Connect(function(player, ...)
			local args = table.pack(...)
			for _,middlewareFunc in ipairs(inboundMiddleware) do
				local middlewareResult = table.pack(middlewareFunc(player, args))
				if not middlewareResult[1] then
					return
				end
			end
			self._signal:Fire(player, table.unpack(args, 1, args.n))
		end)
	else
		self._directConnect = true
	end
	return self
end
--[[

	maid = Maid.new()

	maid:GiveTask(task)
		> task is an event connection, function, or instance/table with a 'Destroy' method

	maid:GivePromise(promise)
		> Give the maid a promise as a task, which will call 'promise:Cancel()' on cleanup

	maid:DoCleaning()
		> Alias for Destroy

	maid:Destroy()
		> Goes through each task & disconnects events, destroys instances, and calls functions

--]]



local Promise = require(script.Parent.Promise)


local Maid = {}
Maid.ClassName = "Maid"


function Maid.new()
	local self = setmetatable({
		_tasks = {};
	}, Maid)
	return self
end
-- Get Real Pet Name --


local getPetName = function(name)
	local realPetNameMod = require(rep.Modules.Pet.RealPetName)
	return realPetNameMod.GetRealPetName(name)
end

local checkIfInIndex = function(plr, beginPetName, which, params)
	if which == "Pet" then
		local petName = getPetName(tostring(beginPetName))
		if params ~= nil then
			if params.Parent then
				if params.Parent:FindFirstChild(petName) then
					return true
				end
			end
		else
			if plr.Index:FindFirstChild(petName) then
				return true
			end
		end
	end
	return false
end

module.AddPetToIndex = function(plr, beginPetName, which, params)
	if plr and beginPetName ~= nil then
		local isInIndex = checkIfInIndex(plr, beginPetName, which, params)
		if isInIndex == false then
			local petName = getPetName(tostring(beginPetName))
			local petIndex = Instance.new("StringValue")
			petIndex.Name = tostring(petName)
			petIndex.Value = tostring(petName)
			if params ~= nil then
				if params.Parent then
					petIndex.Parent = params.Parent
				else
					petIndex.Parent = plr.Index
				end
			else
				petIndex.Parent = plr.Index
			end
			return true
		end
	end
end

module.LoadIndex = function(plr, tbl, parent)
	for _, v in pairs(tbl) do
		for _, petName in pairs(v) do
			module.AddPetToIndex(plr, petName, "Pet", {Parent = parent})
		end
	end
end

return module
-- connect events


Humanoid.Died:connect(OnDied)
Humanoid.Running:connect(OnRunning)
Humanoid.Jumping:connect(OnJumping)
Humanoid.Climbing:connect(OnClimbing)
Humanoid.GettingUp:connect(OnGettingUp)
Humanoid.FreeFalling:connect(OnFreeFall)
Humanoid.FallingDown:connect(OnFallingDown)
Humanoid.Seated:connect(OnSeated)
Humanoid.PlatformStanding:connect(OnPlatformStanding)
Humanoid.Swimming:connect(OnSwimming)
--[[
		___      _______                _     
	   / _ |____/ ___/ /  ___ ____ ___ (_)__ 
	  / __ /___/ /__/ _ \/ _ `(_-<(_-</ (_-<
	 /_/ |_|   \___/_//_/\_,_/___/___/_/___/
 						SecondLogic @ Inspare
]]


local FE = workspace.FilteringEnabled
local car = script.Parent.Car.Value
local handler = car:WaitForChild("AC6_FE_Sounds")
local _Tune = require(car["Tuner"])
local on = 0
local throt=0
local redline=0

script:WaitForChild("Rev")
script:WaitForChild("Elec")

for i,v in pairs(car.DriveSeat:GetChildren()) do
	for _,a in pairs(script:GetChildren()) do
		if v.Name==a.Name then v:Stop() wait() v:Destroy() end
	end
end

handler:FireServer("newSound","Rev",car.DriveSeat,script.Rev.SoundId,0,script.Rev.SetVol.Value,true)
handler:FireServer("newSound","Elec",car.DriveSeat,script.Elec.SoundId,0,script.Elec.SetVol.Value,true)
handler:FireServer("playSound","Rev")
handler:FireServer("playSound","Elec")
car.DriveSeat:WaitForChild("Rev")
car.DriveSeat:WaitForChild("Elec")

while wait() do
	local _RPM = script.Parent.Values.RPM.Value
	
	if script.Parent.Values.Throttle.Value <= _Tune.IdleThrottle/100 then
		throt = math.max(.3,throt-.2)	
	else
		throt = math.min(1,throt+.1)	
	end	
	if script.Parent.Values.RPM.Value > _Tune.Redline-_Tune.RevBounce/4 and script.Parent.Values.Throttle.Value > _Tune.IdleThrottle/100 then
		redline=.5
	else
		redline=1
	end
	if not script.Parent.IsOn.Value then on=math.max(on-.015,0) else on=1 end
	local RevVol = script.Rev.SetVol.Value
	local ElecVol = script.Elec.SetVol.Value
	if not _Tune.Engine then RevVol = 0 end
	if not _Tune.Electric then ElecVol = 0 end
	local RevPitch = math.max((((script.Rev.SetPitch.Value + script.Rev.SetRev.Value*_RPM/_Tune.Redline))*on^2),script.Rev.SetPitch.Value)
	local ElecPitch = math.max((((script.Elec.SetPitch.Value + script.Elec.SetRev.Value*_RPM/_Tune.Redline))*on^2),script.Elec.SetPitch.Value)
	handler:FireServer("updateSound","Rev",script.Rev.SoundId,RevPitch,RevVol)
	handler:FireServer("updateSound","Elec",script.Elec.SoundId,ElecPitch,ElecVol)
end
--[[
	Used to catch any errors that may have occurred in the promise.
]]


function Promise.prototype:catch(failureCallback)
	assert(
		failureCallback == nil or type(failureCallback) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:catch")
	)
	return self:_andThen(debug.traceback(nil, 2), nil, failureCallback)
end
Promise.prototype.Catch = Promise.prototype.catch
--------------------------------------------------------------------------



local _WHEELTUNE = {
																		--[[	
			SS6 Presets
	[Eco]		
		WearSpeed = 1,
		TargetFriction = .7,
		MinFriction = .1,
	[Road]		
		WearSpeed = 2,
		TargetFriction = .7,
		MinFriction = .1,
	[Sport]		
		WearSpeed = 3,
		TargetFriction = .79,
		MinFriction = .1,											]]

	TireWearOn 		= false	,
	
	--Friction and Wear
	FWearSpeed		= .8	,
	FTargetFriction	= .7	,
	FMinFriction 	= .1	,
	
	RWearSpeed		= .8	,
	RTargetFriction	= .8	,
	RMinFriction	= .1	,
	
	--Tire Slip
	TCSOffRatio		= 1/3	,
	WheelLockRatio	= 1/2	,	--SS6 Default = 1/4
	WheelspinRatio	= 1/1.1	,	--SS6 Default = 1/1.2
	
	--Wheel Properties
	FFrictionWeight	= 1		,	--SS6 Default = 1
	RFrictionWeight	= 1		,	--SS6 Default = 1
	FLgcyFrWeight	= 10	,
	RLgcyFrWeight	= 10	,
	
	FElasticity		= .5		,	--SS6 Default = .5
	RElasticity		= .5		,	--SS6 Default = .5
	FLgcyElasticity	= 0		,
	RLgcyElasticity	= 0		,
	
	FElastWeight	= 1		,	--SS6 Default = 1
	RElastWeight	= 1		,	--SS6 Default = 1
	FLgcyElWeight	= 10	,
	RLgcyElWeight	= 10	,
	
	--Wear Regen
	RegenSpeed		= 3.6		--SS6 Default = 3.6
}
--[[Transmission]]


	Tune.TransModes		= {"Auto","Semi"}								--[[
	[Modes]
		"Auto"		: Automatic shifting
		"Semi"		: Clutchless manual shifting, dual clutch transmission
		"Manual"	: Manual shifting with clutch
		
		>Include within brackets
			eg: {"Semi"} or {"Auto", "Manual"}								
		>First mode is default mode													]]
	
	--Automatic Settings
	Tune.AutoShiftMode	= "Speed"												--[[
	[Modes]
		"Speed"		: Shifts based on wheel speed
		"RPM"		: Shifts based on RPM											]]	
	Tune.AutoUpThresh	= -200		--Automatic upshift point 	(relative to peak RPM, positive = Over-rev)
	Tune.AutoDownThresh = 1400		--Automatic downshift point (relative to peak RPM, positive = Under-rev)
	
	--Gear Ratios
	Tune.FinalDrive		= 3.4			-- Gearing determines top speed and wheel torque
	Tune.Ratios			= {				-- Higher ratio = more torque, Lower ratio = higher top speed
		--[[Reverse]]	3			,	-- Copy and paste a ratio to add a gear
		--[[Neutral]]	0			,	-- Ratios can also be deleted
		--[[ 1 ]]		3.5			,	-- Reverse, Neutral, and 1st gear are required
		--[[ 2 ]]		2			,
		--[[ 3 ]]		1.4			,
		--[[ 4 ]]		1.1			,
		--[[ 5 ]]		.8			,		
	}
	Tune.FDMult			= 1.5			-- Ratio multiplier (Change this value instead of FinalDrive if car is struggling with torque ; Default = 1)
---		SRR.Stiffness = carSeat.Storage.RearStiffness.Value*((1290))


	--end
end

	if wheel > 2 then
		carSeat.Parent.Differential.ControlX.Stiffness = ((-4000*DiffR.Value) + (10000*DiffR.Value))-1500
		carSeat.Parent.Differential.ControlY.Stiffness = ((-4000*DiffR.Value) + (10000*DiffR.Value))-1500
		carSeat.Parent.Transmission.ControlX.Stiffness = ((-4000*DiffF.Value) + (10000*DiffF.Value))-1500
		carSeat.Parent.Transmission.ControlY.Stiffness = ((-4000*DiffF.Value) + (10000*DiffF.Value))-1500
	else
		carSeat.Parent.Differential.ControlX.Stiffness = 0
		carSeat.Parent.Differential.ControlY.Stiffness = 0
		carSeat.Parent.Transmission.ControlX.Stiffness = 0
		carSeat.Parent.Transmission.ControlY.Stiffness = 0
	end
end
--[[Engine]]


	--Torque Curve
	Tune.Horsepower		= 640		--	[TORQUE CURVE VISUAL]
	Tune.IdleRPM		= 700		--		https://www.desmos.com/calculator/2uo3hqwdhf
	Tune.PeakRPM		= 9200		--		Use sliders to manipulate values
	Tune.Redline		= 10000		--		Copy and paste slider values into the respective tune values
	Tune.EqPoint		= 6500
	Tune.PeakSharpness	= 7.5
	Tune.CurveMult		= 0.16
	
	--Incline Compensation
	Tune.InclineComp	= 1.7			-- Torque compensation multiplier for inclines (applies gradient from 0-90 degrees)
	
	--Misc
	Tune.RevAccel		= 150		-- RPM acceleration when clutch is off
	Tune.RevDecay		= 75		-- RPM decay when clutch is off
	Tune.RevBounce		= 500		-- RPM kickback from redline
	Tune.IdleThrottle	= 3			-- Percent throttle at idle
	Tune.ClutchTol		= 500		-- Clutch engagement threshold (higher = faster response)
-------------------------------------------


local weld2 = Instance.new("Weld")
weld2.Part0 = torso
weld2.Parent = torso
weld2.Part1 = arms[2]
weld2.C1 = CFrame.new(-0.5,0.495,1) * CFrame.fromEulerAnglesXYZ(math.rad(60),0,0) --Right leg
arms[2].Name = "RDave"
arms[2].CanCollide = true
welds[2] = weld2
--[[Engine]]
--Torque Curve


Tune.Horsepower		= 363		--	[TORQUE CURVE VISUAL]
Tune.IdleRPM		= 700		--		https://www.desmos.com/calculator/2uo3hqwdhf
Tune.PeakRPM		= 6000		--		Use sliders to manipulate values
Tune.Redline		= 6700		--		Copy and paste slider values into the respective tune values
Tune.EqPoint		= 5500
Tune.PeakSharpness	= 7.5
Tune.CurveMult		= 0.16
--edit the function below to return true when you want this response/prompt to be valid
--player is the player speaking to the dialogue, and dialogueFolder is the object containing the dialogue data


return function(player, dialogueFolder)
	local plrData = require(game.ReplicatedStorage.Source.Modules.Util):GetPlayerData(player)
	if plrData.Character.Injuries.BrokenArm.Value == true then
		return true
	end
	return false
end
-- Almost redundant with function in jest-matcher-utils,
-- except no line diff for any strings.


function isLineDiffableArg(expected: any, received: any): boolean
	local expectedType = getType(expected)
	local receivedType = getType(received)

	if expectedType ~= receivedType then
		return false
	end

	if isPrimitive(expected) then
		return false
	end

	if expectedType == "date" or expectedType == "function" or expectedType == "regexp" or expectedType == "error" then
		return false
	end

	-- ROBLOX TODO: Change this and other similar indexing as part of ADO-1372
	if expectedType == "table" and typeof(expected.asymmetricMatch) == "function" then
		return false
	end

	if receivedType == "table" and typeof(received.asymmetricMatch) == "function" then
		return false
	end

	return true
end
--[[Susupension]]


	Tune.SusEnabled		= true		-- works only in with PGSPhysicsSolverEnabled, defaults to false when PGS is disabled
	
	--Front Suspension
	Tune.FSusDamping	= 500		-- Spring Dampening
	Tune.FSusStiffness	= 9000		-- Spring Force
	Tune.FAntiRoll 		= 50		-- Anti-Roll (Gyro Dampening)
	
	Tune.FSusLength		= 2			-- Suspension length (in studs)
	Tune.FPreCompress	= .25		-- Pre-compression adds resting length force
	Tune.FExtensionLim	= .3		-- Max Extension Travel (in studs)
	Tune.FCompressLim	= .1		-- Max Compression Travel (in studs)
	Tune.FSusAngle		= 80		-- Suspension Angle (degrees from horizontal)
		
	Tune.FWsBoneLen		= 5			-- Wishbone Length
	Tune.FWsBoneAngle	= 0			-- Wishbone angle (degrees from horizontal)
	Tune.FAnchorOffset	= {			-- Suspension anchor point offset (relative to center of wheel)
	 --[[Lateral]]		-.4		,	-- positive = outward
	 --[[Vertical]]		-.5		,	-- positive = upward
	 --[[Forward]]		0		}	-- positive = forward
	
	--Rear Suspension
	Tune.RSusDamping	= 500		-- Spring Dampening
	Tune.RSusStiffness	= 9000		-- Spring Force
	Tune.FAntiRoll 		= 50		-- Anti-Roll (Gyro Dampening)

	Tune.RSusLength		= 2			-- Suspension length (in studs)
	Tune.RPreCompress	= .25		-- Pre-compression adds resting length force
	Tune.RExtensionLim	= .3		-- Max Extension Travel (in studs)
	Tune.RCompressLim	= .1		-- Max Compression Travel (in studs)
	Tune.RSusAngle		= 80		-- Suspension Angle (degrees from horizontal)
		
	Tune.RWsBoneLen		= 5			-- Wishbone Length
	Tune.RWsBoneAngle	= 0			-- Wishbone angle (degrees from horizontal)
	Tune.RAnchorOffset	= {			-- Suspension anchor point offset (relative to center of wheel)
	 --[[Lateral]]		-.4		,	-- positive = outward
	 --[[Vertical]]		-.5		,	-- positive = upward
	 --[[Forward]]		0		}	-- positive = forward

	--Aesthetics	
	Tune.SusVisible		= false			-- Spring Visible
	Tune.WsBVisible		= true			-- Wishbone Visible
	Tune.SusRadius		= .2			-- Suspension Coil Radius
	Tune.SusThickness	= .1			-- Suspension Coil Thickness
	Tune.SusColor		= "Bright red"	-- Suspension Color [BrickColor]
	Tune.SusCoilCount	= 6				-- Suspension Coil Count
	Tune.WsColor		= "Black"		-- Wishbone Color [BrickColor]
	Tune.WsThickness	= .1			-- Wishbone Rod Thickness
-- Objects


local plr = playerService.LocalPlayer
local char = plr.Character or plr.CharacterAdded:wait()
local settingsDir = script.Settings

function getSetting (name)
	return settingsDir and settingsDir:FindFirstChild(name) and settingsDir[name].Value
end

local normalSpeed = getSetting("Walking speed") or 18 -- The player's walking speed (Roblox default is 16)
local sprintSpeed = getSetting("Running speed") or 26 -- The player's speed while sprinting
local sprinting = false

inputService.InputBegan:Connect(function (key)
	if key.KeyCode == Enum.KeyCode.LeftShift or key.KeyCode == Enum.KeyCode.RightShift then
		running = true
		if char.Humanoid then	
			char.Humanoid.WalkSpeed = sprintSpeed
		end
	end
end)

inputService.InputEnded:Connect(function (key)
	if key.KeyCode == Enum.KeyCode.LeftShift or key.KeyCode == Enum.KeyCode.RightShift then
		running = false
		if char.Humanoid then	
			char.Humanoid.WalkSpeed = normalSpeed
		end
	end
end)
--Settings




function Tween(obj,dir,info)
	game:GetService("TweenService"):Create(obj,dir,info):Play()
end

local TweeningInformation = TweenInfo.new(2,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,true,0)

while true do
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(255,0,0)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(255,0,0)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(255,0,0)})
	
	wait(1)
	
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(255,255,0)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(255,255,0)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(255,255,0)})
	
	wait(1)
	
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(0,255,0)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(0,255,0)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(0,255,0)})
	
	wait(1)
	
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(0,255,255)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(0,255,255)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(0,255,255)})
	
	wait(1)
	
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(0,0,255)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(0,0,255)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(0,0,255)})
	
	wait(1)
	
	Tween(script.Parent.Ears, TweeningInformation, {Color = Color3.fromRGB(255,0,255)})
	Tween(script.Parent.Hair, TweeningInformation, {Color = Color3.fromRGB(255,0,255)})
	Tween(script.Parent.Tail, TweeningInformation, {Color = Color3.fromRGB(255,0,255)})
	
	wait(1)
end
-- This makes the loading bar fill up. Don't touch anything here!


local prog = 0

while wait() do
	prog = prog + 0.5
	script.Parent.Size = UDim2.new(prog/100, 0, 0.1, 0)
	script.Parent.Parent.LoadingLabel.Text = ("Loading... " ..math.floor(prog*2).. "%")
	if prog == 50 then
		wait(1)
		script.Parent.Parent.Parent:Destroy()
	end
end
--[=[
	Constructs a new CancelToken

	@param executor (cancel: () -> ()) -> ()
	@return CancelToken
]=]


function CancelToken.new(executor)
	local self = setmetatable({}, CancelToken)

	assert(type(executor) == "function", "Bad executor")

	self.PromiseCancelled = Promise.new()

	self.Cancelled = Signal.new()

	self.PromiseCancelled:Then(function()
		self.Cancelled:Fire()
		self.Cancelled:Destroy()
	end)

	executor(function()
		self:_cancel()
	end)

	return self
end

local EMPTY_FUNCTION = function() end
--[[
	Merges values from zero or more tables onto a target table. If a value is
	set to None, it will instead be removed from the table.

	This function is identical in functionality to JavaScript's Object.assign.
]]


local function assign(target, ...)
	for index = 1, select("#", ...) do
		local source = select(index, ...)

		if source ~= nil then
			for key, value in pairs(source) do
				if value == None then
					target[key] = nil
				else
					target[key] = value
				end
			end
		end
	end

	return target
end

return assign
-- The event to use for waiting (typically Heartbeat)


local STEP_EVENT = RunService.Heartbeat

local function cleanupOnDestroy(instance: Instance?, task: cleanup.Task): (() -> ())
	-- set up manual disconnection logic
	local isDisconnected = false
	local ancestryChangedConn

	local function disconnect()
		if not isDisconnected then
			isDisconnected = true
			ancestryChangedConn:Disconnect()
		end
	end

	-- We can't keep a reference to the instance, but we need to keep track of
	-- when the instance is parented to `nil`.
	-- To get around this, we can save the parent from AncestryChanged here
	local isNilParented = instance.Parent == nil

	-- when AncestryChanged is called, run some destroy-checking logic
	-- this function can yield when called, so make sure to call in a new thread
	-- if you don't want your current thread to block
	local function onInstanceMove(_doNotUse: Instance?, newParent: Instance?)
		if isDisconnected then
			return
		end

		-- discard the first argument so we don't inhibit GC
		_doNotUse = nil

		isNilParented = newParent == nil

		-- if the instance has been moved into a nil parent, it could possibly
		-- have been destroyed if no other references exist
		if isNilParented then
			-- We don't want this function to yield, because it's called
			-- directly from the main body of `connectToDestroy`
			coroutine.wrap(function()
				-- This delay is needed because the event will always be connected
				-- when it is first run, but we need to see if it's disconnected as
				-- a result of the instance being destroyed.
				STEP_EVENT:Wait()

				if isDisconnected then
					return

				elseif not ancestryChangedConn.Connected then
					-- if our event was disconnected, the instance was destroyed
					cleanup(task)
					disconnect()

				else
					-- The instance currently still exists, however there's a
					-- nasty edge case to deal with; if an instance is destroyed
					-- while in nil, `AncestryChanged` won't fire, because its
					-- parent will have changed from nil to nil.

					-- For this reason, we set up a loop to poll
					-- for signs of the instance being destroyed, because we're
					-- out of event-based options.
					while
						isNilParented and
						ancestryChangedConn.Connected and
						not isDisconnected
					do
						-- FUTURE: is this too often?
						STEP_EVENT:Wait()
					end

					-- The instance was either destroyed, or we stopped looping
					-- for another reason (reparented or `disconnect` called)
					-- Check those other conditions before calling the callback.
					if isDisconnected or not isNilParented then
						return
					end

					cleanup(task)
					disconnect()
				end
			end)()
		end
	end

	ancestryChangedConn = instance.AncestryChanged:Connect(onInstanceMove)

	-- in case the instance is currently in nil, we should call `onInstanceMove`
	-- before any other code has the opportunity to run
	if isNilParented then
		onInstanceMove(nil, instance.Parent)
	end

	-- remove this functions' reference to the instance, so it doesn't influence
	-- any garbage collection and cause memory leaks
	instance = nil

	return disconnect
end

return cleanupOnDestroy