Pinkstack/roblox-luau-corpus-text huggingface dataset:
-- emote bindable hook


if FFlagAnimateScriptEmoteHook then
	script:WaitForChild("PlayEmote").OnInvoke = function(emote)
		-- Only play emotes when idling
		if pose ~= "Standing" then
			return
		end
	
		if emoteNames[emote] ~= nil then
			-- Default emotes
			playAnimation(emote, EMOTE_TRANSITION_TIME, Humanoid)
			
			if userPlayEmoteByIdAnimTrackReturn then
				return true, currentAnimTrack
			else
				return true
			end
		elseif typeof(emote) == "Instance" and emote:IsA("Animation") then
			-- Non-default emotes
			playEmote(emote, EMOTE_TRANSITION_TIME, Humanoid)

			if userPlayEmoteByIdAnimTrackReturn then
				return true, currentAnimTrack
			else
				return true
			end
		end
		
		-- Return false to indicate that the emote could not be played
		return false
	end
end
-- Colors


local FriendlyReticleColor = Color3.new(0, 1, 0)
local EnemyReticleColor	= Color3.new(1, 0, 0)
local NeutralReticleColor	= Color3.new(1, 1, 1)

local Spread = MinSpread
local AmmoInClip = ClipSize

local Camera = workspace.CurrentCamera

local Tool = script.Parent
local Handle = WaitForChild(Tool, 'Handle')
local WeaponGui = nil
--[[**
	ensures value is an enum of the correct type

	@param enum The enum to check

	@returns A function that will return true iff the condition is passed
**--]]


function t.enum(enum)
	assert(t.Enum(enum))
	return function(value)
		local enumItemSuccess, enumItemErrMsg = t.EnumItem(value)
		if not enumItemSuccess then
			return false, enumItemErrMsg
		end

		if value.EnumType == enum then
			return true
		else
			return false, string.format("enum of %s expected, got enum of %s", tostring(enum), tostring(value.EnumType))
		end
	end
end

do
	local checkWrap = t.tuple(t.callback, t.callback)
-- Sound


CEs.PlaySound.OnClientEvent:connect(function(Sound,Rchr)
	if not Sound then return end
	if not Rchr then
		if Sound:IsDescendantOf(plr.Character) then return end
	else
		if plr.Character == Rchr then return end
	end
	
	local newSound = Instance.new("Sound", Sound.Parent)
	newSound.SoundId = Sound.SoundId
	newSound.PlaybackSpeed = Sound.PlaybackSpeed
	newSound.Volume = Sound.Volume
	newSound.Name = Sound.Name.."Playing"
	newSound:Play()
	game:GetService("Debris"):AddItem(newSound, Sound.TimeLength)
end)

CEs.StopSound.OnClientEvent:connect(function(Sound,Rchr)
	if not Sound then return end
	if not Rchr then
		if Sound:IsDescendantOf(plr.Character) then return end
	else
		if plr.Character == Rchr then return end
	end
	local newSound = Sound.Parent:FindFirstChild(Sound.Name.."Playing")
	if newSound then newSound:Destroy() end
end)
-- Teleport error logging


function Lobby._onTeleportFailure(player, status, message)
	Log.Error.Lobby("Teleport Failed: %s (%s)", player.UserId, message)

	-- Send error back to the server
	local data = {
		type = "FAILURE",
		status = status,
		message = message,
	}
	self.joinEvent:FireServer(data)
end

TeleportService.TeleportInitFailed:Connect(Lobby._onTeleportFailure)
--[[Weight and CG]]


	Tune.Weight			= 1000		-- Total weight (in pounds)
	Tune.WeightBSize	= {			-- Size of weight brick (dimmensions in studs ; larger = more stable)
	 --[[Width]]		6		,
	 --[[Height]]		3.5		,
	 --[[Length]]		14		}
	Tune.WeightDist		= 55		-- Weight distribution (0 - on rear wheels, 100 - on front wheels, can be <0 or >100)
	Tune.CGHeight		= .8		-- Center of gravity height (studs relative to median of all wheels)
	Tune.WBVisible		= false		-- Makes the weight brick visible
	
	--Unsprung Weight
	Tune.FWheelDensity	= .1		-- Front Wheel Density
	Tune.RWheelDensity	= .1		-- Rear Wheel Density
	Tune.FWLgcyDensity	= 1			-- Front Wheel Density [PGS OFF]
	Tune.RWLgcyDensity	= 1			-- Rear Wheel Density [PGS OFF]
	
	Tune.AxleSize		= 2			-- Size of structural members (larger = more stable/carry more weight)
	Tune.AxleDensity	= .1		-- Density of structural members
--[[
class Spring

Description:
	A physical model of a spring, useful in many applications. Properties only evaluate
	upon index making this model good for lazy applications

API:
	Spring = Spring.new(number position)
		Creates a new spring in 1D
	Spring = Spring.new(Vector3 position)
		Creates a new spring in 3D

	Spring.Position
		Returns the current position
	Spring.Velocity
		Returns the current velocity
	Spring.Target
		Returns the target
	Spring.Damper
		Returns the damper
	Spring.Speed
		Returns the speed

	Spring.Target = number/Vector3
		Sets the target
	Spring.Position = number/Vector3
		Sets the position
	Spring.Velocity = number/Vector3
		Sets the velocity
	Spring.Damper = number [0, 1]
		Sets the spring damper, defaults to 1
	Spring.Speed = number [0, infinity)
		Sets the spring speed, defaults to 1

	Spring:TimeSkip(number DeltaTime)
		Instantly skips the spring forwards by that amount of now
	Spring:Impulse(number/Vector3 velocity)
		Impulses the spring, increasing velocity by the amount given

Visualization (by Defaultio):
	https://www.desmos.com/calculator/hn2i9shxbz
]]




local Spring = {}
--Weld stuff here



misc:WaitForChild("Spoiler")
MakeWeld(car.DriveSeat,misc.Spoiler:WaitForChild("A1")).Name="W"
MakeWeld(misc.Spoiler.A1,misc.Spoiler:WaitForChild("A2"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.A2,misc.Spoiler:WaitForChild("A3"),"Motor",.02).Name="W"
MakeWeld(misc.Spoiler.A3,misc.Spoiler:WaitForChild("A"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.A3,misc.Spoiler:WaitForChild("A4"),"Motor",.01).Name="P"
MakeWeld(misc.Spoiler.A4,misc.Spoiler:WaitForChild("Sp"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.Sp,misc.Spoiler:WaitForChild("B1"))
MakeWeld(misc.Spoiler.B1,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B2,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B3,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B4,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B5,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B6,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.B7,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"
MakeWeld(misc.Spoiler.RFL,misc.Spoiler:WaitForChild("Paint"),"Motor",.01).Name="W"

car.DriveSeat.ChildAdded:connect(function(child)
	if child.Name=="SeatWeld" and child:IsA("Weld") and game.Players:GetPlayerFromCharacter(child.Part1.Parent)~=nil then
		child.C0=CFrame.new(0,-.5,0)*CFrame.fromEulerAnglesXYZ(-(math.pi/2),0,0)*CFrame.Angles(math.rad(13),0,0)
	end
end)
-- Please don't edit this script



L1 = script.Parent.LED1.Scripts.on
L2 = script.Parent.LED2.Scripts.on
L3 = script.Parent.LED3.Scripts.on
L4 = script.Parent.LED4.Scripts.on
L5 = script.Parent.LED5.Scripts.on

R1 = script.Parent.Parent.Relays.Relay1
R2 = script.Parent.Parent.Relays.Relay2
R3 = script.Parent.Parent.Relays.Relay3
R4 = script.Parent.Parent.Relays.Relay4
R5 = script.Parent.Parent.Relays.Relay5

repeat task.wait()
	L1.Value = R1.RelayOn.Value
	L2.Value = R2.RelayOn.Value
	L3.Value = R3.RelayOn.Value
	L4.Value = R4.RelayOn.Value
	L5.Value = R5.RelayOn.Value
until script.Enabled == false
--[=[
	Extracts the locale from the name
	@param localeId string -- the defaultlocaleId
	@param dataTable table -- Data table to load from
	@return LocalizationTable
]=]


function JsonToLocalizationTable.loadTable(localeId, dataTable)
	local localizationTable = JsonToLocalizationTable.getOrCreateLocalizationTable()

	recurseAdd(localizationTable, localeId, "", dataTable)

	return localizationTable
end
--[[ Local Functions ]]

--
function MouseLockController:OnMouseLockToggled()
	self.isMouseLocked = not self.isMouseLocked

	if self.isMouseLocked then
		local cursorImageValueObj = script:FindFirstChild("CursorImage")
		if cursorImageValueObj and cursorImageValueObj:IsA("StringValue") and cursorImageValueObj.Value then
			self.savedMouseCursor = Mouse.Icon
			Mouse.Icon = cursorImageValueObj.Value
		else
			if cursorImageValueObj then
				cursorImageValueObj:Destroy()
			end
			cursorImageValueObj = Instance.new("StringValue")
			cursorImageValueObj.Name = "CursorImage"
			cursorImageValueObj.Value = DEFAULT_MOUSE_LOCK_CURSOR
			cursorImageValueObj.Parent = script
			self.savedMouseCursor = Mouse.Icon
			Mouse.Icon = DEFAULT_MOUSE_LOCK_CURSOR
		end
	else
		if self.savedMouseCursor then
			Mouse.Icon = self.savedMouseCursor
			self.savedMouseCursor = nil
		end
	end

	self.mouseLockToggledEvent:Fire()
end

function MouseLockController:DoMouseLockSwitch(name, state, input)
	if state == Enum.UserInputState.Begin then
		self:OnMouseLockToggled()
		return Enum.ContextActionResult.Sink
	end
	return Enum.ContextActionResult.Pass
end

function MouseLockController:BindContextActions()
	ContextActionService:BindActionAtPriority(CONTEXT_ACTION_NAME, function(name, state, input)
		return self:DoMouseLockSwitch(name, state, input)
	end, false, MOUSELOCK_ACTION_PRIORITY, unpack(self.boundKeys))
end

function MouseLockController:UnbindContextActions()
	ContextActionService:UnbindAction(CONTEXT_ACTION_NAME)
end

function MouseLockController:IsMouseLocked()
	return self.enabled and self.isMouseLocked
end

function MouseLockController:EnableMouseLock(enable)
	if enable ~= self.enabled then

		self.enabled = enable

		if self.enabled then
			-- Enabling the mode
			self:BindContextActions()
		else
			-- Disabling
			-- Restore mouse cursor
			if Mouse.Icon~="" then
				Mouse.Icon = ""
			end

			self:UnbindContextActions()

			-- If the mode is disabled while being used, fire the event to toggle it off
			if self.isMouseLocked then
				self.mouseLockToggledEvent:Fire()
			end

			self.isMouseLocked = false
		end

	end
end

return MouseLockController
--Variables


local SeatInteractionCount = {}

local VehicleSeating = {}

local function getVehicleObject()
	return script.Parent.Parent
end

local function carjackingEnabled(obj)
	return obj:GetAttribute("AllowCarjacking")
end

local function getEffectsFolderFromSeat(seat)
	local parent = seat.Parent
	if parent:IsA("Model") then
		if parent:FindFirstChild("Effects") then
			return parent.Effects
		else
			return getEffectsFolderFromSeat(parent)
		end
	end
	return nil
end

local function playDoorSound(seat, sound)
	local sound = seat:FindFirstChild(sound.."Door")
	if sound then
		sound:Play()
	end
end
--		Humanoid:UnequipTools()
--		if tool then
--			Humanoid:EquipTool(tool)
--		end


		for i,v in pairs(Char:GetChildren()) do
			if v:IsA('Tool') then
				v.Parent = Backpack
			end
		end
		if tool then
			tool.Parent = Char
			tool.Unequipped:connect(function()
				wait()
				EquippedVal.Value = getSlotFromTool(Char:FindFirstChildOfClass('Tool'))
				--EquippedVal.Value = nil
			end)
		end
		
		if tool == nil then
			EquippedVal.Value = nil
		end
	end
	
	-- Takes Enum.KeyCode and gets string at end
	local function getKeyCodeName(keycode)
		keycode = tostring(keycode)
		local splitStrings = string.split(keycode,'.')
		return splitStrings[#splitStrings]
	end
	
	-- Equips whatever the Equipped Obj's value is
	EquippedVal.Changed:Connect(function()
		local equipSlot = EquippedVal.Value
		if equipSlot then
			equip(equipSlot.Value)
		else
			equip(nil)
		end
	end)
	
	-- ensure equipped items replicate when changed
	for i,v in pairs(SlotsFolder:GetChildren()) do
		v.Changed:connect(function()
			if EquippedVal.Value == v then
				wait() -- required to prevent slot duping
				equip(v.Value)
			end
		end)
	end
	
	-- Checks keyboard input
	UserInputService.InputBegan:Connect(function(input, gameProcessed)
		if not gameProcessed then -- Ensures user is not typing in TextBox
			-- Ensures user is using keybooard
			if input.UserInputType == Enum.UserInputType.Keyboard then
				-- Get the KeyCode and KeyCode's ending/name
				local keyPressed = input.KeyCode
				keyPressed = getKeyCodeName(keyPressed)
				-- Checks if there is a slot w/ the pressed key's name
				local slotRequested = SlotsFolder:FindFirstChild(keyPressed)
				if slotRequested then -- if there is such a slot
					-- if they're requesting the same slot
					if EquippedVal.Value == slotRequested then 
						EquippedVal.Value = nil -- unequip the tool
					else
						EquippedVal.Value = slotRequested -- equip the tool
					end
				end
			end
		end
	end)
	
	return EquippedVal
end
--// No-opt connect Server>Client RemoteEvents to ensure they cannot be called
--// to fill the remote event queue.


local function emptyFunction()
	--intentially empty
end

local function GetObjectWithNameAndType(parentObject, objectName, objectType)
	for i, child in pairs(parentObject:GetChildren()) do
		if (child:IsA(objectType) and child.Name == objectName) then
			return child
		end
	end

	return nil
end

local function CreateIfDoesntExist(parentObject, objectName, objectType)
	local obj = GetObjectWithNameAndType(parentObject, objectName, objectType)
	if (not obj) then
		obj = Instance.new(objectType)
		obj.Name = objectName
		obj.Parent = parentObject
	end
	useEvents[objectName] = obj

	return obj
end
--Suspension Placement--



local SFL = FL:Clone()
SFL.Name = "FL"
SFL.CanCollide = false
SFL.Parent = script.Parent.Parent
SFL.CFrame = SFL.CFrame + (Vector3.new(SFL.Size.X,SFL.Size.X,SFL.Size.X) * SFL.CFrame.upVector)
SFL.Attachment.Rotation = Vector3.new(0,0,90)

local SFR = FR:Clone()
SFR.Name = "FR"
SFR.CanCollide = false
SFR.Parent = script.Parent.Parent
SFR.CFrame = SFR.CFrame + (Vector3.new(SFL.Size.X,SFL.Size.X,SFL.Size.X) * SFR.CFrame.upVector)
SFR.Attachment.Rotation = Vector3.new(0,0,90)

local SRL = RL:Clone()
SRL.Name = "RL"
SRL.CanCollide = false
SRL.Parent = script.Parent.Parent
SRL.CFrame = SRL.CFrame + (Vector3.new(SFL.Size.X,SFL.Size.X,SFL.Size.X) * SRL.CFrame.upVector)
SRL.Attachment.Rotation = Vector3.new(0,0,90)

local SRR = RR:Clone()
SRR.Name = "RR"
SRR.CanCollide = false
SRR.Parent = script.Parent.Parent
SRR.CFrame = SRR.CFrame + (Vector3.new(SFL.Size.X,SFL.Size.X,SFL.Size.X) * SRR.CFrame.upVector)
SRR.Attachment.Rotation = Vector3.new(0,0,90)
-- Implements Javascript's `Array.prototype.reduce` as defined below
-- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
-- TODO Luau: when Luau supports overloads, use them here so that reduceFn can correctly use T when initialValue (U) isn't supplied


return function<T, U>(array: Array<T>, callback: reduceFn<T, U>, initialValue: U?): U
	if _G.__DEV__ then
		if typeof(array) ~= "table" then
			error(string.format("Array.reduce called on %s", typeof(array)))
		end
		if typeof(callback) ~= "function" then
			error("callback is not a function")
		end
	end

	local length = #array

	local value: T | U
	local initial = 1

	if initialValue ~= nil then
		value = initialValue
	else
		initial = 2
		if length == 0 then
			error("reduce of empty array with no initial value")
		end
		value = array[1]
	end

	for i = initial, length do
		value = callback(value :: U, array[i], i, array)
	end

	return value :: U
end
--returns the wielding player of this tool


function getPlayer()
	local char = Tool.Parent
	return game:GetService("Players"):GetPlayerFromCharacter(Character)
end

function Toss(direction)
	local OriginalWalkSpeed = Humanoid.WalkSpeed
	OriginalWalkSpeed = OriginalWalkSpeed
	Humanoid.WalkSpeed = 0
	local handlePos = Vector3.new(Tool.Handle.Position.X, 0, Tool.Handle.Position.Z)
	local spawnPos = Character.Head.Position
	spawnPos  = spawnPos + (direction * 5)
	Tool.Handle.Transparency = 1
	local Object = Tool.Handle:Clone()
	Object.Parent = workspace
	Object.Transparency = 0
	Object.Swing.Pitch = math.random(90, 110)/100
	Object.Swing:Play()
	Object.CanCollide = true
	Object.CFrame = Tool.Handle.CFrame
	Object.Velocity = (direction*AttackVelocity) + Vector3.new(0,AttackVelocity/7.5,0)
	local rand = 11.25
	Object.RotVelocity = Vector3.new(math.random(-rand,rand),math.random(-rand,rand),math.random(-rand,rand))
	Object:SetNetworkOwner(getPlayer())
	local ScriptClone = DamageScript:Clone()
	ScriptClone.FriendlyFire.Value = FriendlyFire
	ScriptClone.Damage.Value = AttackDamage
	ScriptClone.Parent = Object
	ScriptClone.Disabled = false
	local tag = Instance.new("ObjectValue")
	tag.Value = getPlayer()
	tag.Name = "creator"
	tag.Parent = Object
	Humanoid.WalkSpeed = OriginalWalkSpeed
	Tool:Destroy()
end

Remote.OnServerEvent:Connect(function(player, mousePosition)
	if not AttackAble then return end
	AttackAble = false
	if Humanoid and Humanoid.RigType == Enum.HumanoidRigType.R15 then
		Remote:FireClient(getPlayer(), "PlayAnimation", "Animation")
	end
	local targetPos = mousePosition.p
	local lookAt = (targetPos - Character.Head.Position).unit
	Toss(lookAt)
	LeftDown = true
end)

function onLeftUp()
	LeftDown = false
end

Tool.Equipped:Connect(function()
	Character = Tool.Parent
	Humanoid = Character:FindFirstChildOfClass("Humanoid")
end)

Tool.Unequipped:Connect(function()
	Character = nil
	Humanoid = nil
end)
--[=[
	@within Plasma
	@function button
	@tag widgets
	@param label string -- The label for the checkbox
	@return ButtonWidgetHandle

	A text button.

	Returns a widget handle, which has the field:

	- `clicked`, a function you can call to check if the checkbox was clicked this frame

	![A button](https://i.eryn.io/2150/RobloxStudioBeta-iwRM0RMx.png)

	```lua
	Plasma.window("Button", function()
		if Plasma.button("button text"):clicked() then
			print("clicked!")
		end
	end)
	```
]=]



local Runtime = require(script.Parent.Parent.Runtime)
local Style = require(script.Parent.Parent.Style)
local create = require(script.Parent.Parent.create)

return Runtime.widget(function(text)
	local clicked, setClicked = Runtime.useState(false)
	local refs = Runtime.useInstance(function(ref)
		local style = Style.get()

		return create("TextButton", {
			[ref] = "button",
			BackgroundColor3 = style.bg3,
			BorderSizePixel = 0,
			Font = Enum.Font.SourceSans,
			Size = UDim2.new(0, 100, 0, 40),
			TextColor3 = style.textColor,
			AutomaticSize = Enum.AutomaticSize.X,
			TextSize = 21,

			create("UIPadding", {
				PaddingLeft = UDim.new(0, 10),
				PaddingRight = UDim.new(0, 10),
			}),

			create("UICorner"),

			Activated = function()
				setClicked(true)
			end,
		})
	end)

	local instance = refs.button

	instance.Text = text

	local handle = {
		clicked = function()
			if clicked then
				setClicked(false)
				return true
			end

			return false
		end,
	}

	return handle
end)
--Services


local pathfindingService = game:GetService("PathfindingService")
local runService = game:GetService("RunService")

local modules = script.Parent
local core = require(modules.CoreModule)
local status = require(modules.Status)
local troubleshoot = require(modules.Troubleshoot)

local marine = script.Parent.Parent.Parent
local myHuman = marine.Humanoid
local myRoot = marine.HumanoidRootPart


local moveEvent = Instance.new("BindableEvent")
function movement.moveToFinished()
	local success = true
	local completed = false
    
    core.spawn(function() 
        wait(1)
		if not completed then
	        success = false
	        moveEvent:Fire()   
		end
    end)
    
    core.spawn(function()
        myHuman.MoveToFinished:Wait()
        moveEvent:Fire()
    end)
    
	moveEvent.Event:Wait()

	completed = true

    return success
end

local path = pathfindingService:CreatePath()
function movement.pathToLocation(target)
	if not target or not target.Parent then return end
	
	path:ComputeAsync(myRoot.Position, target.Position)
	
	if path.Status == Enum.PathStatus.NoPath then
		return
	end
	
	local waypoints = path:GetWaypoints()
	
	--Make sure that path is actually valid
	if waypoints[1] and core.checkDist(waypoints[1],myRoot) > 10 then
		runService.Heartbeat:Wait()
		movement.pathToLocation(target)
	end
	
	troubleshoot.visualizePath(path)
	
	for _,waypoint in ipairs(waypoints) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			myHuman.Jump = true
		end
		myHuman:MoveTo(waypoint.Position)
		core.spawn(function()
			while myHuman.WalkToPoint.Y > myRoot.Position.Y - 1 do
				wait(0.1)
				myHuman.Jump = true
			end
		end)
		local moveSuccess = movement.moveToFinished()
		local dist = core.checkDist(myRoot,target)
		local canSee = core.checkSight(target)
		if not moveSuccess or not target.Parent or (dist < 30 and canSee) or status:get("currentTarget") ~= target then
			break
		elseif (core.checkSight(target) and target.Position.Y <= myRoot.Position.Y-5) then
			myHuman:MoveTo(myRoot.Position)
			break
		end
		if core.checkDist(target,waypoints[#waypoints]) > 30 then
			--movement.pathToLocation(target)
			break
		end
	end
end

function movement.walkRandom()
	local randX = math.random(-100,100)
	local randZ = math.random(-100,100)
	local goal = myRoot.Position + Vector3.new(randX, 0, randZ)
	local path = pathfindingService:CreatePath()
	path:ComputeAsync(myRoot.Position, goal)
	local waypoints = path:GetWaypoints()
	
	if path.Status == Enum.PathStatus.Success then
		for i,waypoint in ipairs(waypoints) do
			if waypoint.Action == Enum.PathWaypointAction.Jump then
				myHuman.Jump = true
			end
			myHuman:MoveTo(waypoint.Position)
			core.spawn(function()
				wait(0.5)
				if myHuman.WalkToPoint.Y > myRoot.Position.Y then
					myHuman.Jump = true
				end
			end)
			local moveSuccess = myHuman.MoveToFinished:Wait()
			if not moveSuccess or status:get("currentTarget") then
				break
			end
		end
	else
		wait(2)
	end
end
--[[
	Returns a new promise that:
		* is resolved when all input promises resolve
		* is rejected if ANY input promises reject
]]


function Promise._all(traceback, promises, amount)
	if type(promises) ~= "table" then
		error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
	end

	-- We need to check that each value is a promise here so that we can produce
	-- a proper error rather than a rejected promise with our error.
	for i, promise in pairs(promises) do
		if not Promise.is(promise) then
			error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
		end
	end

	-- If there are no values then return an already resolved promise.
	if #promises == 0 or amount == 0 then
		return Promise.resolve({})
	end

	return Promise._new(traceback, function(resolve, reject, onCancel)
		-- An array to contain our resolved values from the given promises.
		local resolvedValues = {}
		local newPromises = {}

		-- Keep a count of resolved promises because just checking the resolved
		-- values length wouldn't account for promises that resolve with nil.
		local resolvedCount = 0
		local rejectedCount = 0
		local done = false

		local function cancel()
			for _, promise in ipairs(newPromises) do
				promise:cancel()
			end
		end

		-- Called when a single value is resolved and resolves if all are done.
		local function resolveOne(i, ...)
			if done then
				return
			end

			resolvedCount = resolvedCount + 1

			if amount == nil then
				resolvedValues[i] = ...
			else
				resolvedValues[resolvedCount] = ...
			end

			if resolvedCount >= (amount or #promises) then
				done = true
				resolve(resolvedValues)
				cancel()
			end
		end

		onCancel(cancel)

		-- We can assume the values inside `promises` are all promises since we
		-- checked above.
		for i, promise in ipairs(promises) do
			newPromises[i] = promise:andThen(function(...)
				resolveOne(i, ...)
			end, function(...)
				rejectedCount = rejectedCount + 1

				if amount == nil or #promises - rejectedCount < amount then
					cancel()
					done = true

					reject(...)
				end
			end)
		end

		if done then
			cancel()
		end
	end)
end