Pinkstack/roblox-luau-corpus-text huggingface dataset:
--[[
	Intended for use in tests.

	Similar to await(), but instead of yielding if the promise is unresolved,
	_unwrap will throw. This indicates an assumption that a promise has
	resolved.
]]


function Promise.prototype:_unwrap()
	if self._status == Promise.Status.Started then
		error("Promise has not resolved or rejected.", 2)
	end

	local success = self._status == Promise.Status.Resolved

	return success, unpack(self._values, 1, self._valuesLength)
end

function Promise.prototype:_resolve(...)
	if self._status ~= Promise.Status.Started then
		if Promise.is((...)) then
			(...):_consumerCancelled(self)
		end
		return
	end

	-- If the resolved value was a Promise, we chain onto it!
	if Promise.is((...)) then
		-- Without this warning, arguments sometimes mysteriously disappear
		if select("#", ...) > 1 then
			local message = (
				"When returning a Promise from andThen, extra arguments are " ..
				"discarded! See:\n\n%s"
			):format(
				self._source
			)
			warn(message)
		end

		local promise = (...):andThen(
			function(...)
				self:_resolve(...)
			end,
			function(...)
				self:_reject(...)
			end
		)

		if promise._status == Promise.Status.Cancelled then
			self:cancel()
		elseif promise._status == Promise.Status.Started then
			-- Adopt ourselves into promise for cancellation propagation.
			self._parent = promise
			promise._consumers[self] = true
		end

		return
	end

	self._status = Promise.Status.Resolved
	self._valuesLength, self._values = pack(...)

	-- We assume that these callbacks will not throw errors.
	for _, callback in ipairs(self._queuedResolve) do
		callback(...)
	end

	self:_finalize()
end

function Promise.prototype:_reject(...)
	if self._status ~= Promise.Status.Started then
		return
	end

	self._status = Promise.Status.Rejected
	self._valuesLength, self._values = pack(...)

	-- If there are any rejection handlers, call those!
	if not isEmpty(self._queuedReject) then
		-- We assume that these callbacks will not throw errors.
		for _, callback in ipairs(self._queuedReject) do
			callback(...)
		end
	else
		-- At this point, no one was able to observe the error.
		-- An error handler might still be attached if the error occurred
		-- synchronously. We'll wait one tick, and if there are still no
		-- observers, then we should put a message in the console.

		local err = tostring((...))

		spawn(function()
			-- Someone observed the error, hooray!
			if not self._unhandledRejection then
				return
			end

			-- Build a reasonable message
			local message = ("Unhandled promise rejection:\n\n%s\n\n%s"):format(
				err,
				self._source
			)
			warn(message)
		end)
	end

	self:_finalize()
end
--Playing the revive animation locally works a lot better than playing it server side


function game.ReplicatedStorage.RemoteFunctions.ReviveAnimation.OnClientInvoke(bodyPartsLocationTable, lastBranch)
	local respawnPosition = player.Character.Torso.CFrame
	for i = 1, #bodyPartsLocationTable["Head"] do
		if lastBranch ~= nil then
			if player.Character.Torso.Position.Z > lastBranch then
				break
			end
		end
		game:GetService("RunService").RenderStepped:wait()
		for key, value in pairs(bodyPartsLocationTable) do
			if player.Character:FindFirstChild(key) then
				if value[i] then
					player.Character[key].CFrame = value[i]
				end
			end
		end
		respawnPosition = player.Character.Torso.CFrame
	end
	player.Character:Destroy()
	return respawnPosition
end
--[=[
	Maps a number from one range to another.

	:::note
	Note the mapped value can be outside of the initial range,
	which is very useful for linear interpolation.
	:::

	```lua
	print(Math.map(0.1, 0, 1, 1, 0)) --> 0.9
	```

	@param num number
	@param min0 number
	@param max0 number
	@param min1 number
	@param max1 number
	@return number
]=]


function Math.map(num: number, min0: number, max0: number, min1: number, max1: number): number
	if max0 == min0 then
		error("Range of zero")
	end

	return (((num - min0)*(max1 - min1)) / (max0 - min0)) + min1
end
--!strict
--[=[
	@function findLast
	@within Array

	@param array {T} -- The array to search.
	@param value? any -- The value to search for.
	@param from? number -- The index to start searching from.
	@return number? -- The index of the last item in the array that matches the value.

	Finds the index of the last item in the array that matches the value.

	```lua
	local array = { "hello", "world", "hello" }

	local index = FindLast(array, "hello") -- 3
	local index = FindLast(array, "hello", 2) -- 1
	```
]=]


local function findLast<T>(array: { T }, value: any?, from: number?): number?
	local length = #array

	from = if type(from) == "number" then if from < 1 then length + from else from else length

	for index = from, 1, -1 do
		if array[index] == value then
			return index
		end
	end

	return
end

return findLast
-- constants



local PLAYER	= Players.LocalPlayer

local ELECTROCUTE_AMOUNT	= 2
local VELOCITY_AMOUNT		= 10

return function(character)
	local effects	= character.Effects
	local parts		= {}
	
	for _, v in pairs(character:GetChildren()) do
		if v:IsA("BasePart") and v.Transparency ~= 1 then
			table.insert(parts, v)
			local rate	= math.floor((v.Size.X + v.Size.Y + v.Size.Z) * ELECTROCUTE_AMOUNT)
			
			local emitter1	= script.ElectricityEmitter1:Clone()
				emitter1.Rate	= rate
				emitter1.Parent	= v
				
			local emitter2	= script.ElectricityEmitter2:Clone()
				emitter2.Rate	= rate
				emitter2.Parent	= v
		end
	end
	
	for i = 1, 100 do
		for _, v in pairs(parts) do
			v.RotVelocity	= Vector3.new(math.random(-VELOCITY_AMOUNT, VELOCITY_AMOUNT), math.random(-VELOCITY_AMOUNT, VELOCITY_AMOUNT), math.random(-VELOCITY_AMOUNT, VELOCITY_AMOUNT))
		end
		wait(0.1)
	end
end
--[[ 

--[Create a table containing some percentages, example table:

     local GuitarChances = {["Red"] = 50, ["Blue"] = 25, ["Green"] = 10}
     
     --you don't have to make the addition of the chances equal to 100, the script will auto-convert the chances.
     
  ]
  
--[Next Step, call the function and get the result! Example = 

        local GuitarChances = {["Red"] = 50, ["Blue"] = 25, ["Green"] = 10}
        
        local SelectedGuitarColor = Roll(GuitarChances)
        
        print(SelectedGuitarColor)
        
        (this script will print a random guitar color with the chances In the table.)
        
        
]

pls leave a like if you don't mind :D
]]



function Roll(Chances)
	local summary = 0

	for index, chance in pairs(Chances) do
		summary += chance
	end

	local NewChances = table.clone(Chances)

	for index, Chance in pairs(NewChances) do
		NewChances[index] = summary / (100 / Chance)
	end

	task.wait()

	local RandomNumber = math.random(summary)

	for index, chance in pairs(NewChances) do

		local Result = index

		local StartPoint, EndPoint = chance, 0

		for NextIndex, NextChance in pairs(NewChances) do
			if NextChance < chance  then
				StartPoint += NextChance; EndPoint += NextChance
			elseif NextChance == chance and NextIndex ~= index then
				StartPoint += NextChance

				local Set = math.random(1,2)

				if Set > 1 then
					Result = NextIndex
				end	
			end
		end

		if RandomNumber > EndPoint and RandomNumber <= StartPoint then

			return Result

		end

	end

end
--[[Drivetrain]]

	
	Tune.Config			= "AWD"		--"FWD" , "RWD" , "AWD"
	
	--Differential Settings	
	Tune.FDiffSlipThres	= 20		-- 1 - 100%				(Max threshold of applying full lock determined by deviation from avg speed)
	Tune.FDiffLockThres	= 30		-- 0 - 100%				(0 - Bias toward slower wheel, 100 - Bias toward faster wheel)
	Tune.RDiffSlipThres	= 40		-- 1 - 100%
	Tune.RDiffLockThres	= 50		-- 0 - 100%
	Tune.CDiffSlipThres	= 60		-- 1 - 100%				[AWD Only]
	Tune.CDiffLockThres	= 70		-- 0 - 100%				[AWD Only]
	
	--Traction Control Settings
	Tune.TCSEnabled		= true		-- Implements TCS
	Tune.TCSThreshold	= 20		-- Slip speed allowed before TCS starts working (in SPS)
	Tune.TCSGradient	= 20		-- Slip speed gradient between 0 to max reduction (in SPS)
	Tune.TCSLimit		= 10		-- Minimum amount of torque at max reduction (in percent)
--[[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 		= 1000		-- Anti-Roll (Gyro Dampening)
	
	Tune.FSusLength		= 2			-- Suspension length (in studs)
	Tune.FPreCompress	= .3		-- 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	= .3		-- 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		= true			-- Spring Visible
	Tune.WsBVisible		= true			-- Wishbone Visible
	Tune.SusRadius		= .2			-- Suspension Coil Radius
	Tune.SusThickness	= .1			-- Suspension Coil Thickness
	Tune.SusColor		= "Hot pink"	-- Suspension Color [BrickColor]
	Tune.SusCoilCount	= 6				-- Suspension Coil Count
	Tune.WsColor		= "Black"		-- Wishbone Color [BrickColor]
	Tune.WsThickness	= .1			-- Wishbone Rod Thickness
-- (Hat Giver Script - Loaded.)



debounce = true

function onTouched(hit)
	if (hit.Parent:findFirstChild("Humanoid") ~= nil and debounce == true) then
		debounce = false
		h = Instance.new("Hat")
		p = Instance.new("Part")
		h.Name = "Top Hat"
		p.Parent = h
		p.Position = hit.Parent:findFirstChild("Head").Position
		p.Name = "Handle" 
		p.formFactor = 0
		p.Size = Vector3.new(2, 1, 1) 
		p.BottomSurface = 0 
		p.TopSurface = 0 
		p.Locked = true 
		script.Parent.Mesh:clone().Parent = p
		h.Parent = hit.Parent
		h.AttachmentPos = Vector3.new(0, .38, 0)
		wait(5)
		debounce = true
	end
end

script.Parent.Touched:connect(onTouched)
-------- OMG HAX



r = game:service("RunService")


local damage = 5


local slash_damage = 8
local lunge_damage = 17

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


local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "rbxasset://sounds\\swordslash.wav"
SlashSound.Parent = sword
SlashSound.Volume = .7

local LungeSound = Instance.new("Sound")
LungeSound.SoundId = "rbxasset://sounds\\swordlunge.wav"
LungeSound.Parent = sword
LungeSound.Volume = .6

local UnsheathSound = Instance.new("Sound")
UnsheathSound.SoundId = "rbxasset://sounds\\unsheath.wav"
UnsheathSound.Parent = sword
UnsheathSound.Volume = 1


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
				tagHumanoid(humanoid, vPlayer)
				humanoid:TakeDamage(damage)
				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 lunge()
	damage = lunge_damage

	LungeSound:play()

	local anim = Instance.new("StringValue")
	anim.Name = "toolanim"
	anim.Value = "Lunge"
	anim.Parent = Tool
	
	
	force = Instance.new("BodyVelocity")
	force.velocity = Vector3.new(0,10,0) --Tool.Parent.Torso.CFrame.lookVector * 80
	force.Parent = Tool.Parent.Torso
	wait(.1)
	swordOut()
	wait(.1)
	force.Parent = nil
	wait(.2)
	swordUp()

	damage = slash_damage
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

function swordAcross()
	-- parry
end


Tool.Enabled = true
local last_attack = 0
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

	t = r.Stepped:wait()

	if (t - last_attack < .2) then
		lunge()
	else
		attack()
	end

	last_attack = t

	--wait(.5)

	Tool.Enabled = true
end


function onEquipped()
	UnsheathSound:play()
end


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


connection = sword.Touched:connect(blow)
--------------------------------------------



local Signal = {}
Signal.__index = Signal


function Signal.new()
	local self = setmetatable({
		_bindable = Instance.new("BindableEvent");
		_connections = {};
		_args = {};
		_threads = 0;
		_id = 0;
	}, Signal)
	return self
end


function Signal.Is(obj)
	return (type(obj) == "table" and getmetatable(obj) == Signal)
end


function Signal:Fire(...)
	local id = self._id
	self._id = self._id + 1
	self._args[id] = {#self._connections + self._threads, {n = select("#", ...), ...}}
	self._threads = 0
	self._bindable:Fire(id)
end


function Signal:Wait()
	self._threads = self._threads + 1
	local id = self._bindable.Event:Wait()
	local args = self._args[id]
	args[1] = args[1] - 1
	if (args[1] <= 0) then
		self._args[id] = nil
	end
	return table.unpack(args[2], 1, args[2].n)
end


function Signal:WaitPromise()
	return Promise.new(function(resolve)
		resolve(self:Wait())
	end)
end


function Signal:Connect(handler)
	local connection = Connection.new(self, self._bindable.Event:Connect(function(id)
		local args = self._args[id]
		args[1] = args[1] - 1
		if (args[1] <= 0) then
			self._args[id] = nil
		end
		handler(table.unpack(args[2], 1, args[2].n))
	end))
	table.insert(self._connections, connection)
	return connection
end


function Signal:DisconnectAll()
	for _,c in ipairs(self._connections) do
		if (c._conn) then
			c._conn:Disconnect()
		end
	end
	self._connections = {}
	self._args = {}
end


function Signal:Destroy()
	self:DisconnectAll()
	self._bindable:Destroy()
end


function Signal:Init()
	Promise = self.Shared.Promise
end


return Signal
--Internal Settings--



local fullMag = 30

local spread = 1.1 -- in degrees

local fullauto = true -- shoots all bullets as long as the player is visible (boolean)

local burstamount = 3 -- (only works if full auto is off) amount of times gun fires in burst fire mode

local firerate = 0.08 -- in seconds

local shotgunpellets = 1 -- setting this above 1 turns the gun into a shotgun (MIGHT LAG WITH FULL AUTO ON)

local delaybeforereloading = 0.3 -- to delay reload (prevents the marine from shooting the last shot of the mag at the ground)

local MinimumDamage,MaximumDamage = 9, 13 -- the amount of damage each bullet does (RANDOMIZED) first value is minimum, second value is maximum

local headshotmultiplier = 2 -- self explanitory (set this value to 1 if you dont want a multiplier)

local HitWallSounds = {"rbxassetid://6962153997","rbxassetid://6962154328","rbxassetid://6962154691","rbxassetid://6962155018","rbxassetid://6962155378"} -- basically sounds for hitting walls

local HitFleshSound = "rbxassetid://4988621968" -- plays when a creature gets shot

local bulletacceleration = Vector3.new(0,0,0) -- very similar to how acceleration works in particle emitters (setting the y value to a negative number will give the bullet bulletdrop)

local maxdistance = 300

local bulletspeed = 400
-----------------
--| Variables |--
-----------------



local Tool = script.Parent

local ScytheEquipAnimation = WaitForChild(script, 'ScytheEquip2')
local ScytheIdleAnimation = WaitForChild(script, 'ScytheIdle2')
local ScytheSlashAnimation = WaitForChild(script, 'ScytheSlash')

local ScytheEquipTrack = nil
local ScytheIdleTrack = nil
local ScytheSlashTrack = nil
--local busy = false
--Shield.Touched:connect(function(Hit)
--	if Hit == nil then return end
--	if Hit.Parent == nil then return end
--	if busy == true then return end
--	
--	busy = true	
--	
--	local Item = Hit.Parent
--	
--	if Item:IsA("Tool") == true then return end
--	if Hit.Name == "Torso" then return end
--	if Hit.Name == "HumanoidRootPart" then return end
--	if Hit.Name == "Left Leg" then return end
--	if Hit.Name == "Right Leg" then return end
--	if Hit.Name == "Head" then return end
--	if Hit.Name == "Left Arm" then return end
--	if Hit.Name == "Right Arm" then return end
--	
--	if Game:GetService("Players"):GetPlayerFromCharacter(Item) ~= nil then return end
--	
--	local touch = false
--	for _, x in ipairs(Hit:GetChildren()) do
--		if x:IsA("TouchTransmitter") == true then touch = true x:Destroy() break end
--	end
--	
--	local owner, dmg = GetOwnerAndDamage(Hit)
--	if owner ~= nil and dmg ~= nil then
--		if Health > 0 then
--			if Health >= dmg then
--				Health = Health - dmg
--				
--				if Health < 0 then Health = 0 end
--				
--				HealthBar.Shield.Bar:TweenSize(UDim2.new((Health / MaxHealth), 0, 1, 0), Enum.EasingDirection.In, Enum.EasingStyle.Linear, 0.5, true)
--				
--				if Health > 0 then
--					-- yay, still alive.
--				else
--					HealthBar.Parent.Parent:Destroy()
--				end
--				
--				Hit:Destroy()
--			else
--				HealthBar.Parent.Parent:Destroy()
--			end
--		else
--			HealthBar.Parent.Parent:Destroy()
--		end
--	else
--		if touch == true then
--			--Hit:Destroy()
--		end
--	end
--	
--	busy = false
--end)
-- Setup animation objects


function scriptChildModified(child)
	local fileList = animNames[child.Name]
	if (fileList ~= nil) then
		configureAnimationSet(child.Name, fileList)
	else
		if child:isA("StringValue") then
			animNames[child.Name] = {}
			configureAnimationSet(child.Name, animNames[child.Name])
		end
	end
end

script.ChildAdded:connect(scriptChildModified)
script.ChildRemoved:connect(scriptChildModified)
--- TagHumanoid


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
--RedEgg--



Event.Hitbox.Touched:Connect(function(hit)
	if hit.Parent:IsA("Tool") and hit.Parent.Name == ToolRequired1 then
		if game.ReplicatedStorage.ItemSwitching.Value == true then
			hit.Parent:Destroy()
		end
		Event.Hitbox.RedGearHint:Destroy()
		Event.RedGear.Transparency = 0
		Event.Glass.Insert:Play()
		Event.LocksLeft.Value = Event.LocksLeft.Value - 1
		script.Disabled = true
	end
end)

Event.Hitbox.ClickDetector.MouseClick:Connect(function(plr)
	if plr.Backpack:FindFirstChild(ToolRequired1) then
		if game.ReplicatedStorage.ItemSwitching.Value == true then
			plr.Backpack:FindFirstChild(ToolRequired1):Destroy()
		end
		Event.Hitbox.RedGearHint:Destroy()
		Event.RedGear.Transparency = 0
		Event.Glass.Insert:Play()
		Event.LocksLeft.Value = Event.LocksLeft.Value - 1
		script.Disabled = true
	end
end)
--Changes the size of the part----------


local function ModifyScale(Scale, Plot, Grid, Model)
	X, Y, Z = unpack(Scale)
	
	if X == "" or Y == "" or Z == "" then
		X = random:NextInteger(1, Plot.Size.X/5)
		Y = random:NextInteger(1, 20)
		Z = random:NextInteger(1, Plot.Size.Z/5)
	end
	
	X = math.clamp(tonumber(X), 1, 78)
	Y = math.clamp(tonumber(Y), 1, 512)
	Z = math.clamp(tonumber(Z), 1, 78)
	
	Confirm(Grid, Plot)
	
	Model.PrimaryPart.Size = Vector3.new(X, Y, Z)
	Model.Hull.Size = Model.PrimaryPart.Size
	
	return true
end
--[=[
	Returns a tuple of fail and complete functions which
	can be chained into the the next subscription.

	```lua
	return function(source)
		return Observable.new(function(sub)
			return source:Subscribe(function(result)
				sub:Fire(tostring(result))
			end, sub:GetFailComplete()) -- Reuse is easy here!
		end)
	end
	```

	@return function
	@return function
]=]


function Subscription:GetFailComplete()
	return function(...)
		self:Fail(...)
	end, function(...)
		self:Complete(...)
	end
end
--game.Players.PlayerAdded:Connect(function(p)
--	phs:CreateCollisionGroup(p.Name)
--	phs:CollisionGroupSetCollidable(p.Name,p.Name,true)
--	for i,v in pairs(game.Players:GetChildren()) do
--		if v ~= p then
--			phs:CollisionGroupSetCollidable(p.Name,v.Name,false)
--		end
--	end
--	p.CharacterAdded:connect(function(c)
--		for i,v in pairs(c:GetChildren()) do
--			if v:IsA("BasePart") then
--				phs:SetPartCollisionGroup(v,p.Name)
--			end
--		end
--		c.ChildAdded:connect(function(v)
--			if v:IsA("BasePart") then
--				phs:SetPartCollisionGroup(v,p.Name)
--			end
--		end)
--	end)
--end)
--
--game.Players.PlayerRemoving:Connect(function(p)
--	phs:RemoveCollisionGroup(p.Name)
--end)
-- If you want to know how to retexture a hat, read this:  http://www.roblox.com/Forum/ShowPost.aspx?PostID=10502388










debounce = true

function onTouched(hit)
	if (hit.Parent:findFirstChild("Humanoid") ~= nil and debounce == true) then
		debounce = false
		h = Instance.new("Hat")
		p = Instance.new("Part")
		h.Name = "Hat"   -- It doesn't make a difference, but if you want to make your place in Explorer neater, change this to the name of your hat.
		p.Parent = h
		p.Position = hit.Parent:findFirstChild("Head").Position
		p.Name = "Handle" 
		p.formFactor = 0
		p.Size = Vector3.new(-0,-0,-1) 
		p.BottomSurface = 0 
		p.TopSurface = 0 
		p.Locked = true 
		script.Parent.Mesh:clone().Parent = p
		h.Parent = hit.Parent
		h.AttachmentPos = Vector3.new(0, -0.95, 0) -- Change these to change the positiones of your hat, as I said earlier.
		wait(5)		debounce = true
	end
end

script.Parent.Touched:connect(onTouched)
--[[
local TypeDefs = require(script.TypeDefinitions)
type CanPierceFunction = TypeDefs.CanPierceFunction
type GenericTable = TypeDefs.GenericTable
type Caster = TypeDefs.Caster
type FastCastBehavior = TypeDefs.FastCastBehavior
type CastTrajectory = TypeDefs.CastTrajectory
type CastStateInfo = TypeDefs.CastStateInfo
type CastRayInfo = TypeDefs.CastRayInfo
type ActiveCast = TypeDefs.ActiveCast
--]]