Roblox/luau_corpus huggingface dataset:
-- functions

local function Raycast(position, direction, ignore)
	local ray		= Ray.new(position, direction)
	local success	= false
	local h, p, n, humanoid
	
	table.insert(ignore, Workspace.Effects)
	
	repeat
		h, p, n	= Workspace:FindPartOnRayWithIgnoreList(ray, ignore)
		
		if h then
			humanoid	= h.Parent:FindFirstChildOfClass("Humanoid")
			if humanoid and humanoid.Health <= 0 then
				humanoid	= nil
			end
			if humanoid then
				success	= true
			else
				if h.CanCollide and h.Transparency < 1 then
					success	= true
				else
					table.insert(ignore, h)
					success	= false
				end
			end
		else
			success	= true
		end
	until success
	
	return h, p, n, humanoid
end
--Scripts
UserInputService.InputBegan:Connect(function(key) --When player holds shift key, run code
 if key.KeyCode == Enum.KeyCode.LeftShift then
 Character.Humanoid.WalkSpeed = SpeedBoost
 end 
end)

UserInputService.InputEnded:Connect(function(key)-- When player lets go of shift key, run code
 if key.KeyCode == Enum.KeyCode.LeftShift then
 Character.Humanoid.WalkSpeed = DefaultSpeed
 end
end)
-------- OMG HAX

r = game:service("RunService")


local damage = 5


local slash_damage = 20


sword = script.Parent.Handle
Tool = script.Parent


SlashSound = sword.Swoosh1

function isTurbo(character)
	return character:FindFirstChild("PaperHat") ~= nil
end


function blow(hit)

	local humanoid = hit.Parent:findFirstChild("Humanoid")
	local vCharacter = Tool.Parent
	local vPlayer = game.Players:playerFromCharacter(vCharacter)
	local hum = vCharacter:findFirstChild("Humanoid") -- non-nil if tool held by a character
	if humanoid~=nil and humanoid ~= hum and hum ~= nil then
		-- final check, make sure sword is in-hand

		local right_arm = vCharacter:FindFirstChild("Right Arm")
		if (right_arm ~= nil) then
			local joint = right_arm:FindFirstChild("RightGrip")
			if (joint ~= nil and (joint.Part0 == sword or joint.Part1 == sword)) then
				local d = damage
				if (isTurbo(vCharacter) == true) then d = d * 2.5 end
				tagHumanoid(humanoid, vPlayer)
				humanoid:TakeDamage(d)
				sword.Splat.Volume = 1
				wait(1)
				untagHumanoid(humanoid)
			end
		end


	end
end


function tagHumanoid(humanoid, player)
	local creator_tag = Instance.new("ObjectValue")
	creator_tag.Value = player
	creator_tag.Name = "creator"
	creator_tag.Parent = humanoid
end

function untagHumanoid(humanoid)
	if humanoid ~= nil then
		local tag = humanoid:findFirstChild("creator")
		if tag ~= nil then
			tag.Parent = nil
		end
	end
end


function attack()
	damage = slash_damage
	SlashSound:play()
	local anim = Instance.new("StringValue")
	anim.Name = "toolanim"
	anim.Value = "Slash"
	anim.Parent = Tool
end


function swordUp()
	Tool.GripForward = Vector3.new(-1,0,0)
	Tool.GripRight = Vector3.new(0,1,0)
	Tool.GripUp = Vector3.new(0,0,1)
end

function swordOut()
	Tool.GripForward = Vector3.new(0,0,1)
	Tool.GripRight = Vector3.new(0,-1,0)
	Tool.GripUp = Vector3.new(-1,0,0)
end



Tool.Enabled = true

function onActivated()

	if not Tool.Enabled then
		return
	end

	Tool.Enabled = false

	local character = Tool.Parent;
	local humanoid = character.Humanoid
	if humanoid == nil then
		print("Humanoid not found")
		return 
	end

	

	attack()

	wait(2.2)

	sword.Splat.Volume = 0
	Tool.Enabled = true


end


function onEquipped()
	sword.Splat.Volume = 0
	SlashSound:play()
end


script.Parent.Activated:connect(onActivated)
script.Parent.Equipped:connect(onEquipped)


connection = sword.Touched:connect(blow)
-- When someone steps on the food, drop what they're holding and attach the food to them along with an eatingScript
-- (They must: Not be the creator, be alive, have a right arm, not be eating, and not be poisoned)
Food.Touched:connect(function(otherPart)
	if otherPart and otherPart.Parent and otherPart.Parent:IsA("Model") and otherPart.Parent ~= creator then
		local otherModel = otherPart.Parent
		if otherModel:FindFirstChild("Humanoid") and otherModel.Humanoid.Health > 0 and otherModel:FindFirstChild("Right Arm") then
			local otherHumanoid = otherModel.Humanoid
			if not otherHumanoid:FindFirstChild(eatingScript.Name) and not otherHumanoid:FindFirstChild("Poisoned") then
				if Food:FindFirstChild("SelfDestruct") then Food.SelfDestruct:Destroy() end -- lol
				if Food:FindFirstChild("BodyGyro") then Food.BodyGyro:Destroy() end
				local children = otherModel:GetChildren()
				for i = 1, #children do -- Remove current Tool
					local child = children[i]
					if child and child:IsA("Tool") then
						child.Parent = Workspace
						break
					end
				end
				Food.Parent = otherModel
				local weld = Instance.new("Weld", Game.JointsService)
				weld.Part0 = otherModel["Right Arm"]
				weld.Part1 = Food
				weld.C1 = CFrame.Angles(math.pi/2, 0, 0) + Vector3.new(0, 0, 1.4)
				local eatingScriptClone = eatingScript:Clone()
				Game:GetService("Debris"):AddItem(eatingScriptClone, 60) -- In case non-player humanoids pick it up
				eatingScriptClone.Parent = otherHumanoid
				eatingScriptClone.Disabled = false
				script:Destroy()
			end
		end
	end
end)
--				AI.Head:BreakJoints()
			if Hit.Name ~= "Torso" and Hit.Name ~= "Head" then
				Hit.CanCollide = true
			else
				Hit.Parent.Humanoid:TakeDamage(0)
			end -- kill

			Logic = 0
			Hit = nil

		elseif Hit.Parent.Name == AIName then
------//Sprinting Animations
self.RightSprint 	= CFrame.new(-1, 1.5, -0.45) * CFrame.Angles(math.rad(-30), math.rad(0), math.rad(0));
self.LeftSprint 	= CFrame.new(1,1.35,-0.75) * CFrame.Angles(math.rad(-30),math.rad(35),math.rad(-25));

return self
-----------------
--| Variables |--
-----------------

local GamePassService = game:GetService('MarketplaceService')
local PlayersService = game:GetService('Players')

local VipDoor = script.Parent

local GamePassIdObject = script:WaitForChild( 'GamePassId')

local JustTouched = {}
-- Convenience function so that calling code does not have to first get the activeController
-- and then call GetMoveVector on it. When there is no active controller, this function returns
-- nil so that this case can be distinguished from no current movement (which returns zero vector).
function ControlModule:GetMoveVector()
	if self.activeController then
		return self.activeController:GetMoveVector()
	end
	return Vector3.new(0,0,0)
end

function ControlModule:GetActiveController()
	return self.activeController
end

function ControlModule:EnableActiveControlModule()
	if self.activeControlModule == ClickToMove then
		-- For ClickToMove, when it is the player's choice, we also enable the full keyboard controls.
		-- When the developer is forcing click to move, the most keyboard controls (WASD) are not available, only jump.
		self.activeController:Enable(
			true,
			Players.LocalPlayer.DevComputerMovementMode == Enum.DevComputerMovementMode.UserChoice,
			self.touchJumpController
		)
	elseif self.touchControlFrame then
		self.activeController:Enable(true, self.touchControlFrame)
	else
		self.activeController:Enable(true)
	end
end

function ControlModule:Enable(enable)
	if not self.activeController then
		return
	end

	if enable == nil then
		enable = true
	end
	if enable then
		self:EnableActiveControlModule()
	else
		self:Disable()
	end
end
--		print("Wha " .. pose)
		stopAllAnimations()
		amplitude = 0.1
		frequency = 1
		setAngles = true
	end

	if (setAngles) then
		local desiredAngle = amplitude * math.sin(time * frequency)

		RightShoulder:SetDesiredAngle(desiredAngle + climbFudge)
		LeftShoulder:SetDesiredAngle(desiredAngle - climbFudge)
		RightHip:SetDesiredAngle(-desiredAngle)
		LeftHip:SetDesiredAngle(-desiredAngle)
	end

	-- Tool Animation handling
	local tool = getTool()
	if tool and tool:FindFirstChild("Handle") then
	
		local animStringValueObject = getToolAnim(tool)

		if animStringValueObject then
			toolAnim = animStringValueObject.Value
			-- message recieved, delete StringValue
			animStringValueObject.Parent = nil
			toolAnimTime = time + .3
		end

		if time > toolAnimTime then
			toolAnimTime = 0
			toolAnim = "None"
		end

		animateTool()		
	else
		stopToolAnimations()
		toolAnim = "None"
		toolAnimInstance = nil
		toolAnimTime = 0
	end
end
-- GUI
local weaponsGUI = script.Parent
local weapon1Label = weaponsGUI.Weapon1
local weapon2Label = weaponsGUI.Weapon2
local weapon3Label = weaponsGUI.Weapon3

local primaryWeaponSlot = localPlayer.Backpack:WaitForChild("Primary")
local secondaryWeaponSlot = localPlayer.Backpack:WaitForChild("Secondary")
local tertiaryWeaponSlot = localPlayer.Backpack:WaitForChild("Tertiary")

local heatBar = weaponsGUI.HeatBar
local images = weaponsGUI:WaitForChild("Images")
-- Automatically installs user-added maps on server start.
-- 
-- ForbiddenJ

LogHolder = require(game.ServerScriptService.LogHolder)

MapWorkspace = workspace.MapWorkspace
OwnerMapInstallFolder = game.ServerStorage.Maps

function InstallMap(map)
	local success, messages = script.Parent.InstallMap:Invoke(map)
	local log = LogHolder.new()
	log:BulkLog(messages)
	log:SendToServerLog()
----------------------------------
------------FUNCTIONS-------------
----------------------------------

function Receive(player, action, ...)
	local args = {...}
	if player == User and action == "play" then
		HighlightPianoKey(args[1])
		Connector:FireAllClients("play", User, args[1], Settings.SoundSource.Position, Settings.PianoSoundRange, Settings.PianoSounds)
	elseif player == User and action == "abort" then
		Deactivate()
		if SeatWeld then
			SeatWeld:remove()
		end
	end
end
function Activate(player)
	Connector:FireClient(player, "activate", Settings.CameraCFrame, Settings.PianoSounds)
	User = player
end
function Deactivate()
	Connector:FireClient(User, "deactivate")
	User = nil
end
----- sink plug handler -----

plug.Interactive.ClickDetector.MouseClick:Connect(function()
	if plugged.Value == false then
		plugged.Value = true
		plug.Plug.CFrame = plug.Plug.CFrame * CFrame.new(0, -0.08, 0)
		plug.Interactive.CFrame = plug.Interactive.CFrame * CFrame.new(0, 0.14, 0)
		plug.Shaft.CFrame = plug.Shaft.CFrame * CFrame.new(0, 0.14, 0)
	else
		plugged.Value = false
		plug.Plug.CFrame = plug.Plug.CFrame * CFrame.new(0, 0.08, 0)
		plug.Interactive.CFrame = plug.Interactive.CFrame * CFrame.new(0, -0.14, 0)
		plug.Shaft.CFrame = plug.Shaft.CFrame * CFrame.new(0, -0.14, 0)
	end
end)
-----FPS DATA-----
local FPSHandsEnbled = true --The fps arms visibility when first person is on. true/false to toggle
local AutoFirstPerson = true --Forces the player to firstperson camera. true/false to toggle
--// Handling Settings		
	Firerate = 60 / 600; -- 60 = 1 Minute, 600 = Rounds per that 60 seconds. DO NOT TOUCH THE 60!
	
	FireMode = 2; -- 1 = Semi, 2 = Auto, 3 = Burst, 4 = Bolt Action, 5 = Shot, 6 = Explosive
--		print(animName .. " " .. idx .. " [" .. origRoll .. "]")
		local anim = animTable[animName][idx].anim

		-- load it to the humanoid; get AnimationTrack
		oldAnimTrack = currentAnimTrack
		currentAnimTrack = humanoid:LoadAnimation(anim)
		 
		-- play the animation
		currentAnimTrack:Play(transitionTime)
		currentAnim = animName

		-- set up keyframe name triggers
		if (currentAnimKeyframeHandler ~= nil) then
			currentAnimKeyframeHandler:Disconnect()
		end
		currentAnimKeyframeHandler = currentAnimTrack.KeyframeReached:Connect(keyFrameReachedFunc)
	end
end
-- Tween variables
local tweenInfo = TweenInfo.new(
	TWEEN_TIME,  -- Time
	Enum.EasingStyle.Quad,  -- EasingStyle
	Enum.EasingDirection.InOut,  -- EasingDirection
	-1,  -- RepeatCount (when less than zero the tween will loop indefinitely)
	true  -- Reverses (tween will reverse once reaching its goal)
)
local function startTween()
	-- If the part is already tweening, prevent it from starting a new tween
	if inTween == true then
		return
	end
	-- Calculate new CFrame for part position
	local offsetCFrame = CFrame.new(0, TWEEN_MOVE_DISTANCE, 0)
	local newCFrame = partToTween.CFrame:ToWorldSpace(offsetCFrame)
	-- Create a tween and play it
	local tweenPart = TweenService:Create(partToTween, tweenInfo, {CFrame = newCFrame})
	tweenPart:Play()
	inTween = true
	-- On tween completion, make part ready for another tween
	tweenPart.Completed:Connect(function()
		inTween = false
	end)
end

startTween()
--[[
	Creates the initial systems
]]
function SystemManager.createSystems()
	local generatorModel = CollectionService:GetTagged(Constants.Tag.System.Generator)[1]
	systems.generator = Generator.new(generatorModel)

	local engineModel = CollectionService:GetTagged(Constants.Tag.System.Engine)[1]
	systems.engine = Engine.new(engineModel)

	local gravityModel = CollectionService:GetTagged(Constants.Tag.System.Gravity)[1]
	systems.gravity = Gravity.new(gravityModel)

	local lightsModel = CollectionService:GetTagged(Constants.Tag.System.Lights)[1]
	systems.lights = Lights.new(lightsModel)

	local cameraModel = CollectionService:GetTagged(Constants.Tag.System.Camera)[1]
	systems.camera = Camera.new(cameraModel)

	local shieldModel = CollectionService:GetTagged(Constants.Tag.System.Shield)[1]
	systems.shield = Shield.new(shieldModel)
end
-- Variables
local playerListButton = script.Parent:WaitForChild("Ignore")

local playerListFrame = script.Parent:WaitForChild("MainFrame")
-- Loading
local CutsceneFolder = workspace.Cutscenes:WaitForChild("Run") -- The folder that contains the cutscene data (Cameras...)
local Destroy = true -- Destroy folder after loading? you don't want your player to see your cameras floating around!
local NoYield = false -- Generally you want this to be set to false, because loading takes a little bit of time, and you don't want to interact with the cutscene when it's not loaded
local SafeMode = true -- This is adviced to be turned on, especially if the cutscene folder data is too big to load at one frame. when turned on, it loads a camera every frame, not all at once.

local Cutscene = require(CutsceneModule)

local Demo = Cutscene.new(Camera, Looping, Speed, FreezeControls) -- Create cutscene
Demo:Load(CutsceneFolder, Destroy, NoYield, SafeMode) -- Load cutscene data from folder

local PlayOnPartTouch = script:FindFirstChild("PlayOnPartTouch")
local PlayOnPlayerJoin = script:FindFirstChild("PlayOnPlayerJoin")
local PlayOnCharacterAdded = script:FindFirstChild("PlayOnCharacterAdded")
local PlayOnCharacterDied = script:FindFirstChild("PlayOnCharacterDied")
local PlayOnEventFire = script:FindFirstChild("PlayOnEventFire")
local PlayOnRemoteEventFire = script:FindFirstChild("PlayOnRemoteEventFire")
local ProtectTheCharacterWhilePlaying = script:FindFirstChild("ProtectTheCharacterWhilePlaying")
local CharacterProtector = script:FindFirstChild("CharacterProtector")
local Music = script:FindFirstChild("Music")
local StopMusicWhenFinished = script:FindFirstChild("StopMusicWhenFinished")
local StopOnEventFire = script:FindFirstChild("StopOnEventFire")
local StopOnRemoteEventFire = script:FindFirstChild("StopOnRemoteEventFire")
local PlayOnce = script:FindFirstChild("PlayOnce")
local Debounce = script:FindFirstChild("Cooldown")
local OnFinishedRemove = script:FindFirstChild("OnFinishedRemove")
local bin = true
local Player = game:GetService("Players").LocalPlayer
local CutsceneGui = script:FindFirstChild("Cutscene")
-- toggle pause event
local togglePauseEvent = replicatedStorage.Events.TogglePause
togglePauseEvent.OnServerEvent:Connect((function(player, paused)
	Paused = paused
	togglePauseEvent:FireAllClients(Paused)
end))
----- Local -----

local Player = game:GetService("Players").LocalPlayer
local UserInputService = game:GetService("UserInputService")
local IconosFrame = script.Parent
--[[Driver Handling]]

	--Driver Sit	
	car.DriveSeat.ChildAdded:connect(function(child)
		if child.Name=="SeatWeld" and child:IsA("Weld") and game.Players:GetPlayerFromCharacter(child.Part1.Parent)~=nil then
			--Distribute Client Interface
			local p=game.Players:GetPlayerFromCharacter(child.Part1.Parent)
			car.Body.MainPart.Anchored = false
			car.DriveSeat:SetNetworkOwner(p)
			local g=script.Parent["A-Chassis Interface"]:Clone()
			g.Parent=p.PlayerGui
		end
	end)
	
	--Driver Leave
	car.DriveSeat.ChildRemoved:connect(function(child)
		if child.Name=="SeatWeld" and child:IsA("Weld") then
			--Remove Flip Force
			if car.DriveSeat:FindFirstChild("Flip")~=nil then
				car.DriveSeat.Flip.MaxTorque = Vector3.new()
			end
			
			--Remove Wheel Force
			for i,v in pairs(car.Wheels:GetChildren()) do
				if v:FindFirstChild("#AV")~=nil then
					if v["#AV"]:IsA("BodyAngularVelocity") then
						if v["#AV"].AngularVelocity.Magnitude>0 then
							v["#AV"].AngularVelocity = Vector3.new()
							v["#AV"].MaxTorque = Vector3.new()
						end
					else
						if v["#AV"].AngularVelocity>0 then
							v["#AV"].AngularVelocity = 0
							v["#AV"].MotorMaxTorque = 0
						end
					end
				end
			end
		end
		wait(.2)
		car.Body.MainPart.Anchored = true
	end)
--[[Run]]

	--Print Version
	local ver=require(car["A-Chassis Tune"].README)
	print("//INSPARE: AC6 Loaded - Build "..ver)
	
	--Runtime Loops
	
	-- ~60 c/s
	game["Run Service"].Stepped:connect(function()
		--Steering
		Steering()
		
		--RPM
		RPM()
		
		--Update External Values
		_IsOn = script.Parent.IsOn.Value
		_InControls = script.Parent.ControlsOpen.Value
		script.Parent.Values.Gear.Value = _CGear
		script.Parent.Values.RPM.Value = _RPM
		script.Parent.Values.Horsepower.Value = _HP
		script.Parent.Values.Torque.Value = _HP * _Tune.EqPoint / _RPM
		script.Parent.Values.TransmissionMode.Value = _TMode
		script.Parent.Values.Throttle.Value = _GThrot
		script.Parent.Values.Brake.Value = _GBrake
		script.Parent.Values.SteerC.Value = _GSteerC*(1-math.min(car.Body.CarName.Value.VehicleSeat.Velocity.Magnitude/_Tune.SteerDecay,1-(_Tune.MinSteer/100)))
		script.Parent.Values.SteerT.Value = _GSteerT
		script.Parent.Values.PBrake.Value = _PBrake
		script.Parent.Values.TCS.Value = _TCS
		script.Parent.Values.TCSActive.Value = _TCSActive
		script.Parent.Values.ABS.Value = _ABS
		script.Parent.Values.ABSActive.Value = _ABSActive
		script.Parent.Values.MouseSteerOn.Value = _MSteer
		script.Parent.Values.Velocity.Value = car.Body.CarName.Value.VehicleSeat.Velocity
	end)
	
	-- ~15 c/s
	while wait(.0667) do
		--Power
		Engine()
		
		--Flip
		if _Tune.AutoFlip then Flip() end
	end
-- This is basically a function that finds all unanchored parts and adds them to childList.
-- Note: This should only be run once for each object
function checkObject(obj)
	if (obj ~= hole) and (obj.className == "Part" and obj.Parent~=hole.Parent and obj~=tele1) then
		if (obj.Anchored == false) then
			table.insert(childList, 1, obj)
		end
	elseif (obj.className == "Model") or (obj.className == "Hat") or (obj.className == "Tool") or (obj == workspace) then
		local child = obj:GetChildren()
		for x = 1, #child do
			checkObject(child[x])
		end
		obj.ChildAdded:connect(checkObject)
	end
end

checkObject(workspace)

print("Black Hole script loaded.")

local n = 0
while true do
	if n < #childList then
		n = n + 1
		if n % 800 == 0 then
			wait()
		end
	else
		n = 1
		wait()
	end

	local child = childList[n]
	if (child ~= hole) and (child.className == "Part") and (child.Anchored == false) then
		local relPos = hole.Position - child.Position
		local motivator = child:FindFirstChild("BlackHole Influence")
		if relPos.magnitude * 240 * massConstant < mass then
			if (relPos.magnitude * 320 * massConstant < mass) and (child.Size.z + hole.Size.x >  relPos.magnitude * 2 - 4) then
				mass = mass + child:GetMass()
				table.remove(childList, n)
				n = n - 1 -- This is the reason I need a counter of my own design
			else
				child.CanCollide = false -- I Can assume that things won't escape the black hole.
				if motivator == nil then
					motivator = Instance.new("BodyPosition")
					motivator.Parent = child
					motivator.Name = "BlackHole Influence"
				end
				motivator.position = hole.Position
				motivator.maxForce = Vector3.new(1, 1, 1) * mass * child:GetMass() / (relPos.magnitude * massConstant)
			end
		elseif motivator ~= nil then
			motivator:Remove()
		end
	end
end
-- Cast Ray
castray.OnServerEvent:Connect(function(fired, ray, position)
	local beam = Instance.new("Part")
	
	beam.BrickColor = BrickColor.new("Really red")
	beam.FormFactor = Enum.FormFactor.Custom
	beam.Material = Enum.Material.Neon
	beam.Transparency = 0
	beam.Anchored = true
	beam.Locked = true
	beam.CanCollide = false
	beam.Parent = workspace
	
	local distance = (tool:WaitForChild("Hole").CFrame.p - position).Magnitude
	beam.Size = Vector3.new(0.1, 0.1, distance)
	beam.CFrame = CFrame.new(tool:WaitForChild("Hole").CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
	
	game:GetService("Debris"):AddItem(beam, 0.025)
end)
--[[
	CameraModule - This ModuleScript implements a singleton class to manage the
	selection, activation, and deactivation of the current camera controller,
	character occlusion controller, and transparency controller. This script binds to
	RenderStepped at Camera priority and calls the Update() methods on the active
	controller instances.

	The camera controller ModuleScripts implement classes which are instantiated and
	activated as-needed, they are no longer all instantiated up front as they were in
	the previous generation of PlayerScripts.

	2018 PlayerScripts Update - AllYourBlox	
--]]

local CameraModule = {}
CameraModule.__index = CameraModule

local FFlagUserCameraToggle do
	local success, result = pcall(function()
		return UserSettings():IsUserFeatureEnabled("UserCameraToggle")
	end)
	FFlagUserCameraToggle = success and result
end
--print("health script start")
local humanoid = script.Parent.Parent.Parent.Parent:WaitForChild("Humanoid")
-- Libraries
local RbxUtility = LoadLibrary 'RbxUtility';
local History = require(script.Parent.HistoryModule);
local Support = require(script.Parent.SupportLibrary);
--[[
	Calls the given callback, and stores any used external dependencies.
	Arguments can be passed in after the callback.
	If the callback completed successfully, returns true and the returned value,
	otherwise returns false and the error thrown.
	The callback shouldn't yield or run asynchronously.

	NOTE: any calls to useDependency() inside the callback (even if inside any
	nested captureDependencies() call) will not be included in the set, to avoid
	self-dependencies.
]]

local Package = script.Parent.Parent
local PubTypes = require(Package.PubTypes)
local parseError = require(Package.Logging.parseError)
local sharedState = require(Package.Dependencies.sharedState)

type Set<T> = {[T]: any}

local initialisedStack = sharedState.initialisedStack
local initialisedStackCapacity = 0

local function captureDependencies(
	saveToSet: Set<PubTypes.Dependency>,
	callback: (...any) -> any,
	...
): (boolean, any)

	local prevDependencySet = sharedState.dependencySet
	sharedState.dependencySet = saveToSet

	sharedState.initialisedStackSize += 1
	local initialisedStackSize = sharedState.initialisedStackSize

	local initialisedSet
	if initialisedStackSize > initialisedStackCapacity then
		initialisedSet = {}
		initialisedStack[initialisedStackSize] = initialisedSet
		initialisedStackCapacity = initialisedStackSize
	else
		initialisedSet = initialisedStack[initialisedStackSize]
		table.clear(initialisedSet)
	end

	local data = table.pack(xpcall(callback, parseError, ...))

	sharedState.dependencySet = prevDependencySet
	sharedState.initialisedStackSize -= 1

	return table.unpack(data, 1, data.n)
end

return captureDependencies