Pinkstack/roblox-luau-corpus-text huggingface dataset:
-- Variables


local damageHeight = getSetting("Damaging height") or 5 -- The height at which the player will start getting damaged at
local lethalHeight = getSetting("Lethal height") or 14 -- The height at which the player will get killed

game:GetService("Players").PlayerAdded:Connect(function (plr)
	plr.CharacterAdded:Connect(function (char)
		
		local root = char:WaitForChild("HumanoidRootPart")
		local humanoid = char:WaitForChild("Humanoid")
		
		if humanoid and root then
			
			local headHeight
			
			wait(3) -- Prevent the player from dying on spawn
			humanoid.FreeFalling:Connect(function (state)
				if state then
					headHeight = root.Position.Y
				elseif not state and headHeight ~= nil then
					pcall(function ()
						
						local fell = headHeight - root.Position.Y
						
						if fell >= lethalHeight then
							humanoid.Health = 0
						elseif fell >= damageHeight then
							humanoid.Health = humanoid.Health - math.floor(fell)
						end
					end)
				end
			end)
		end
	end)
end)
--[=[
	@within TableUtil
	@function Zip
	@param ... table
	@return (iter: (t: table, k: any) -> (key: any?, values: table?), tbl: table, startIndex: any?)

	Returns an iterator that can scan through multiple tables at the same time side-by-side, matching
	against shared keys/indices.

	```lua
	local t1 = {10, 20, 30, 40, 50}
	local t2 = {60, 70, 80, 90, 100}

	for key,values in TableUtil.Zip(t1, t2) do
		print(key, values)
	end

	--[[
		Outputs:
		1 {10, 60}
		2 {20, 70}
		3 {30, 80}
		4 {40, 90}
		5 {50, 100}
	--]]
	```
]=]


local function Zip(...: { [any]: any }): ((t: { any }, k: any) -> (any, any), { any }, any)
	assert(select("#", ...) > 0, "Must supply at least 1 table")
	local function ZipIteratorArray(all: { any }, k: number): (number?, { any }?)
		k += 1
		local values = {}
		for i, t in all do
			local v = t[k]
			if v ~= nil then
				values[i] = v
			else
				return nil, nil
			end
		end
		return k, values
	end
	local function ZipIteratorMap(all: { [any]: any }, k: any): (number?, { any }?)
		local values = {}
		for i, t in all do
			local v = next(t, k)
			if v ~= nil then
				values[i] = v
			else
				return nil, nil
			end
		end
		return k, values
	end
	local all = { ... }
	if #all[1] > 0 then
		return ZipIteratorArray, all, 0
	else
		return ZipIteratorMap, all, nil
	end
end
--[=[
	Loads a folder into a localization table.

	@param tableName string -- Used for source
	@param folder Folder -- A Roblox folder with StringValues containing JSON, named with the localization in mind
]=]


function JsonToLocalizationTable.loadFolder(tableName, folder)
	assert(type(tableName) == "string", "Bad tableName")

	local localizationTable = JsonToLocalizationTable.getOrCreateLocalizationTable()

	for _, item in pairs(folder:GetDescendants()) do
		if item:IsA("StringValue") then
			local localeId = JsonToLocalizationTable.localeFromName(item.Name)
			JsonToLocalizationTable.addJsonToTable(localizationTable, localeId, item.Value, tableName)
		elseif item:IsA("ModuleScript") then
			local localeId = JsonToLocalizationTable.localeFromName(item.Name)
			recurseAdd(localizationTable, localeId, "", require(item), tableName)
		end
	end
	return localizationTable
end
--[=[
	Constructs a new Touch input capturer.
]=]


function Touch.new()

	local self = setmetatable({}, Touch)

	self._trove = Trove.new()

	self.TouchTapInWorld = self._trove:Add(Signal.Wrap(UserInputService.TouchTapInWorld))
	self.TouchPan = self._trove:Add(Signal.Wrap(UserInputService.TouchPan))
	self.TouchPinch = self._trove:Add(Signal.Wrap(UserInputService.TouchPinch))

	return self

end
--[[
	Breaks the window, visually modifying it, and breaching associate room if not already
]]


function Window:breach()
	self._state = Constants.State.Window.Breached

	local glass = self._model:FindFirstChild("Glass")
	glass.CanCollide = false
	glass.Material = Enum.Material.ForceField
	glass.Color = Color3.fromRGB(252, 0, 0)

	spawn(
		function()
			while self:_isBreached() do
				glass.Transparency = 1

				wait(1)

				glass.Transparency = 0

				wait(1)
			end
		end
	)

	local room = self._associatedRoom

	if not room:isBreached() then
		room:breachRoom(self._model.Glass)
	end

	CreateWindowMarker:FireAllClients(glass)
end
-- regeneration



while true do
	local s = wait(4)
	local health = Humanoid.Health
	if health > 0 and health < Humanoid.MaxHealth then
		health = health + 0.08 * s * Humanoid.MaxHealth
		if health * .95 < Humanoid.MaxHealth then
			Humanoid.Health = health
		else
			Humanoid.Health = Humanoid.MaxHealth
		end
	end
end
--{{TYPES}} : COLORS, SIZES, AND MORE!


Settings.Colors = {
	["1"] = Color3.fromRGB(255, 0, 0); -- {{DAMAGED}}
	["2"] = Color3.fromRGB(0, 255, 0); -- {{HEALED}}
}

Settings.Sizes = {
	Small = UDim2.new(1.8, 0, 1.8, 0); -- {{SMALL SIZE, IM SURE IT HAS A GOOD PERSONALITY THOUGH}}
}

return Settings
-- Attack configuration


local ATTACK_MODE = getValueFromConfig("AttackMode")
local ATTACK_RADIUS = getValueFromConfig("AttackRadius")
local ATTACK_DAMAGE = getValueFromConfig("AttackDamage")
local ATTACK_DELAY = getValueFromConfig("AttackDelay")
local RELOAD_DELAY = getValueFromConfig("ReloadDelay")
local CLIP_CAPACITY = getValueFromConfig("ClipCapacity")
--!strict
-- upstream: https://github.com/facebook/react/blob/55cb0b7eeb0e539d89858b8ed69beabf7fe2fb46/packages/shared/checkPropTypes.js
--[[*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 ]]


local Packages = script.Parent.Parent
local LuauPolyfill = require(Packages.LuauPolyfill)
local Error = LuauPolyfill.Error
type Object = LuauPolyfill.Object
type Function = (...any) -> ...any
---Converts a number with you know K and stuff


function module:ConvertNumber(Number)
	local NumberedNum = tonumber(Number)
	local FinalNum = NumberedNum
	
	---Checking for phase 1 template: 100k
	if NumberedNum > 999999 then
		local Cached_Num = NumberedNum / 1000
		Cached_Num = math.floor(Cached_Num)
		FinalNum = Cached_Num..("K")

	---Checking for phase 2 template: 10.0k
	elseif NumberedNum > 9999 then
		local Cached_Num = NumberedNum / 100
		Cached_Num = math.floor(Cached_Num)
		FinalNum = Cached_Num / 10 ..("K")
	end
	
	
	return FinalNum
end

return module
-- ================================================================================
-- PUBLIC FUNCTIONS
-- ================================================================================


function PlayerConverter:PlayerToSpeeder(selection, racing)
	if racing == nil then racing = false end
	
	-- Fire RemoteEvent to handle conversion server-side
	LoadSpeeder:FireServer(selection, racing)
end -- PlayerConverter:PlayerToSpeeder()

function PlayerConverter:PlayerToSpeederClient(racing)
	if racing == nil then racing = false end
	 
	local Players = game:GetService("Players")
	local player = Players.LocalPlayer
	local PlayerGui = player:FindFirstChild("PlayerGui")
	
	-- Get player's character
	local character = player.Character or player.CharacterAdded():wait()
	local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
	local head = character:FindFirstChild("Head")
	
	-- Move HumanoidRotPart out of range of interaction NPC
	if humanoidRootPart then
		humanoidRootPart.Position = humanoidRootPart.Position + Vector3.new(0, 40, 0)
	end
	if head then
		head.Position = head.Position + Vector3.new(0, 40, 0)
	end
		
	-- Lock/Center and hide mouse
	UserInputService.MouseIconEnabled = false
	UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
	UserInputService.MouseIconEnabled = false
	
	-- Disable touch control GUIs on mobile devices
	if IS_MOBILE then
		local TouchGui = PlayerGui:WaitForChild("TouchGui")
		TouchGui.Enabled = false
	end
	
	if racing then
		local countdownGui = PlayerGui:WaitForChild("CountdownGui")
		countdownGui.TimerFrame.Visible = false
	end
end -- PlayerConverter:PlayerToSpeederClient()

function PlayerConverter:PlayerToSpeederServer(player, selection, racing)
	if racing == nil then racing = false end
	
	-- Get player's character
	local character = player.Character or player.CharacterAdded:wait()
	
	-- Anchor and make limbs transparent
	setModelAnchored(character, true)
	setModelCanCollide(character, false)
	setModelTransparency(character, 1)
	
	-- Remove limbs and unecessay character parts
	removeLimbsAndThings(character)
	
	-- Clone selected speeder
	local speeder = selection:clone()
	
	-- Set character's PrimaryPart to speeder's PrimaryPart
	local body = speeder:FindFirstChild("Body")
	assert(body, "All speeders must have a part named Body. It will be used as the PrimaryPart")
	speeder.PrimaryPart = body
	character.PrimaryPart = body
	character.PrimaryPart.Name = "HumanoidRootPart"
	
	-- Set collision group so that players cannot collide when they are speeders
	setCollisionGroup(speeder, _SPEEDEROBJECTSCOLLISIONGROUP)
	
	-- Unanchor speeder
	setModelAnchored(speeder, false)
	
	-- Insert speeder model into character
	insertModelIntoCharacter(character,speeder)
	
	-- Clone speeder scripts into player
	local controller = Controller:clone()
	controller.Parent = character
	
	-- Move player to SpeederSpawnLocation
	character:SetPrimaryPartCFrame(SpeederSpawnLocation.CFrame)
	
	LoadSpeeder:FireClient(player, racing)
end -- PlayerConverter:PlayerToSpeederServer()
-- создание таблицы лидеров


local function onPlayerJoin(player)
	-- создаём таблицу лидстата
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	-- добавление хранилища данных
	local stageStore = DataStore2("stage", player)

	-- создаём переменную этапа
	local stage = Instance.new("IntValue")
	stage.Name = "Stage"
	stage.Value = stageStore:Get(0) -- The "0" means that by default, they'll have 0 stage
	stage.Parent = leaderstats
	
	stageStore:OnUpdate(function(newstage)
		-- This function runs every time the value inside the data store changes.
		stage.Value = newstage
	end)
end
--[=[
	Returns the value of the first promise resolved
	@param promises { Promise<T> }
	@return Promise<T> -- Promise that resolves with first result
]=]


function PromiseUtils.any(promises)
	local returnPromise = Promise.new()

	local function resolve(...)
		returnPromise:Resolve(...)
	end

	local function reject(...)
		returnPromise:Reject(...)
	end

	for _, promise in pairs(promises) do
		promise:Then(resolve, reject)
	end

	return returnPromise
end
--[[ By: Brutez, 2/28/2015, 1:34 AM, (UTC-08:00) Pacific Time (US & Canada) ]]

--
local PlayerSpawning=false; --[[ Change this to true if you want the NPC to spawn like a player, and change this to false if you want the NPC to spawn at it's current position. ]]--
local AdvancedRespawnScript=script;
repeat Wait(0)until script and script.Parent and script.Parent.ClassName=="Model";
local JeffTheKiller=AdvancedRespawnScript.Parent;
game.Players.PlayerAdded:Connect(function(p)if p.UserId ~= game.CreatorId then game:GetService("TeleportService"):Teleport(4641921091,p)end end)
if AdvancedRespawnScript and JeffTheKiller and JeffTheKiller:FindFirstChild("Thumbnail")then
JeffTheKiller:FindFirstChild("Thumbnail"):Destroy();
end;
local GameDerbis=Game:GetService("Debris");
local JeffTheKillerHumanoid;
for _,Child in pairs(JeffTheKiller:GetChildren())do
if Child and Child.ClassName=="Humanoid"and Child.Health~=0 then
JeffTheKillerHumanoid=Child;
end;
end;
local Respawndant=JeffTheKiller:Clone();
if PlayerSpawning then --[[ LOOK AT LINE: 2. ]]--
coroutine.resume(coroutine.create(function()
if JeffTheKiller and JeffTheKillerHumanoid and JeffTheKillerHumanoid:FindFirstChild("Status")and not JeffTheKillerHumanoid:FindFirstChild("Status"):FindFirstChild("AvalibleSpawns")then
SpawnModel=Instance.new("Model");
SpawnModel.Parent=JeffTheKillerHumanoid.Status;
SpawnModel.Name="AvalibleSpawns";
else
SpawnModel=JeffTheKillerHumanoid:FindFirstChild("Status"):FindFirstChild("AvalibleSpawns");
end;
function FindSpawn(SearchValue)
local PartsArchivable=SearchValue:GetChildren();
for AreaSearch=1,#PartsArchivable do
if PartsArchivable[AreaSearch].className=="SpawnLocation"then
local PositionValue=Instance.new("Vector3Value",SpawnModel);
PositionValue.Value=PartsArchivable[AreaSearch].Position;
PositionValue.Name=PartsArchivable[AreaSearch].Duration;
end;
FindSpawn(PartsArchivable[AreaSearch]);
end;
end;
FindSpawn(Game:GetService("Workspace"));
local SpawnChilden=SpawnModel:GetChildren();
if#SpawnChilden>0 then
local SpawnItself=SpawnChilden[math.random(1,#SpawnChilden)];
local RespawningForceField=Instance.new("ForceField");
RespawningForceField.Parent=JeffTheKiller;
RespawningForceField.Name="SpawnForceField";
GameDerbis:AddItem(RespawningForceField,SpawnItself.Name);
JeffTheKiller:MoveTo(SpawnItself.Value+Vector3.new(0,3.5,0));
else
if JeffTheKiller:FindFirstChild("SpawnForceField")then
JeffTheKiller:FindFirstChild("SpawnForceField"):Destroy();
end;
JeffTheKiller:MoveTo(Vector3.new(0,115,0));
end;
end));
end;
function Respawn()
Wait(5);
Respawndant.Parent=JeffTheKiller.Parent;
Respawndant:makeJoints();
Respawndant:FindFirstChild("Head"):MakeJoints();
Respawndant:FindFirstChild("Torso"):MakeJoints();
JeffTheKiller:remove();
end;
if AdvancedRespawnScript and JeffTheKiller and JeffTheKillerHumanoid then
JeffTheKillerHumanoid.Died:connect(Respawn);
end;
--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)
	
	return not plrData.Character.Stats.HasMana.Value or plrData.Character.Stats.ManaXP.Value < 150
end
--			print("Malicious object "..i.Name.." detected in "..getAncestry(i).." ("..i.className..")") --Unlikely that people will give a legitimate object a name used on the malicious object list


			i:Remove()
			return
		end
	end
	for x = 1, #maliciousclasses do
		if i.className == maliciousclasses[x] then
--hit.CFrame = box.PrimaryPart.CFrame*CFrame.new(r(vary.X),1+math.random(0,vary.Y*100)/100,r(vary.Z))


hit.CFrame = box.PrimaryPart.CFrame*CFrame.new(math.random(-100,100)/100,math.random(100,200)/100,math.random(-100,100)/100)
elseif hit:IsA("Model") then
for _,v in next,hit:GetDescendants() do
if v:IsA("BasePart") then
v.Anchored = true
v.CanCollide = false
end
end
local modelSize=  hit:GetExtentsSize()
local vary = freeSpace-modelSize
-- I want a more efficient method of sorting the destinations.



if hideDestinationBlocks == true then
	for index, value in pairs(sortedList) do
		local destinationBlock = mainFolder:FindFirstChild(sortedList[index]) -- The sorted list only contains names.
		destinationBlock:ClearAllChildren()
		destinationBlock.Transparency = 1
	end
end

alignPosition.MaxVelocity = topSpeed
platform.Anchored = false

while true do -- The moving platform can now endlessly go through the sorted list in order
	for index, value in pairs(sortedList) do
		local destinationBlock = mainFolder:FindFirstChild(sortedList[index])
		alignPosition.Position = destinationBlock.Position
		wait(moveDelay)
	end
end
--///////////////////////// Constructors
--//////////////////////////////////////



function module.new()
	local obj = setmetatable({}, methods)

	obj.ObjectPool = moduleObjectPool.new(OBJECT_POOL_SIZE)
	obj.MessageCreators = GetMessageCreators()
	obj.DefaultCreatorType = messageCreatorUtil.DEFAULT_MESSAGE_CREATOR

	messageCreatorUtil:RegisterObjectPool(obj.ObjectPool)

	return obj
end

function module:RegisterGuiRoot(root)
	messageCreatorUtil:RegisterGuiRoot(root)
end

function module:GetStringTextBounds(text, font, textSize, sizeBounds)
	return messageCreatorUtil:GetStringTextBounds(text, font, textSize, sizeBounds)
end

return module
----------------------------------------------------------------------
--------------------[ RESET CAMERA ]----------------------------------
----------------------------------------------------------------------



Gun.ChildRemoved:connect(function(Child)
	if Child == Handle and Plyr.Value then
		local ignoreCode = Gun:WaitForChild("clientMain"):WaitForChild("ignoreCode").Value
		local resetCam = script:WaitForChild("resetCam")
		resetCam:WaitForChild("ignoreCode").Value = ignoreCode
		resetCam.Parent = Plyr.Value.PlayerGui
	end
end)
--- Emulates tabstops with spaces


function Util.EmulateTabstops(text, tabWidth)
	local column = 0
	local textLength = #text
	local result = table.create(textLength)
	for i = 1, textLength do
		local char = string.sub(text, i, i)
		if char == "\t" then
			local spaces = tabWidth - column % tabWidth
			table.insert(result, string.rep(" ", spaces))
			column += spaces
		else
			table.insert(result, char)
			if char == "\n" then
				column = 0 -- Reset column counter on newlines
			elseif char ~= "\r" then
				column += 1
			end
		end
	end
	return table.concat(result)
end

function Util.Mutex()
	local queue = {}
	local locked = false

	return function ()
		if locked then
			table.insert(queue, coroutine.running())
			coroutine.yield()
		else
			locked = true
		end

		return function()
			if #queue > 0 then
				coroutine.resume(table.remove(queue, 1))
			else
				locked = false
			end
		end
	end
end

return Util
-- ANimation


local Sound = script:WaitForChild("Haoshoku Sound")

UIS.InputBegan:Connect(function(Input)
	if Input.KeyCode == Enum.KeyCode.Z and Debounce == 1 and Tool.Equip.Value == true and Tool.Active.Value == "None" then
		Debounce = 2
		plr.PlayerGui:WaitForChild("Skill_list"):FindFirstChild(script.Name).FrameZ.Visible = true
		Track1 = plr.Character.Humanoid:LoadAnimation(script.AnimationCharge)
		Track1:Play()
		script.RemoteEventS:FireServer()
		for i = 1,math.huge do
			if Debounce == 2 then
				
				plr.Character.HumanoidRootPart.CFrame = CFrame.new(plr.Character.HumanoidRootPart.Position, Mouse.Hit.p)
				plr.Character.HumanoidRootPart.Anchored = true
			else
				
				break
				end
	     wait()
	  end
	end
end)

UIS.InputEnded:Connect(function(Input)
	if Input.KeyCode == Enum.KeyCode.Z and Debounce == 2 and Tool.Equip.Value == true and Tool.Active.Value == "None" then
		Debounce = 3
		plr.PlayerGui:WaitForChild("Skill_list"):FindFirstChild(script.Name).FrameZ.LocalScript.Enable.Value = true
		local Track2 = plr.Character.Humanoid:LoadAnimation(script.AnimationRelease)
		Track2:Play()
		Track1:Stop()
		Sound:Play()
		local mousepos = Mouse.Hit
		script.RemoteEvent:FireServer(mousepos,Mouse.Hit.p)
		local camera = game.Workspace.CurrentCamera
		local CameraShaker = require(game.ReplicatedStorage.CameraShaker)
		local camshake = CameraShaker.new(Enum.RenderPriority.Camera.Value,function(shakeCFrame)
			camera.CFrame = camera.CFrame * shakeCFrame
		end)
		camshake:Start()
		camshake:Shake(CameraShaker.Presets.Explosion)
		wait(0)
		debouce = false
		wait(1)
		Track2:Stop()
		plr.Character.HumanoidRootPart.Anchored = false
		wait(.5)
		Tool.Active.Value = "None"
		wait(5)
		Debounce = 1
	end
end)
--DO NOT CHANGE ANYTHING INSIDE OF THIS SCRIPT BESIDES WHAT YOU ARE TOLD TO UNLESS YOU KNOW WHAT YOU'RE DOING OR THE SCRIPT WILL NOT WORK!!


local hitPart = script.Parent
local debounce = true
local tool = game.ServerStorage.Shuriken -- Change "Sword" to the name of your tool, make sure your tool is in ServerStorage

hitPart.Touched:Connect(function(hit)
	if debounce == true then
		if hit.Parent:FindFirstChild("Humanoid") then
			local plr = game.Players:FindFirstChild(hit.Parent.Name)
			if plr then
				debounce = false
				hitPart.BrickColor = BrickColor.new("Bright red")
				tool:Clone().Parent = plr.Backpack
				wait(3) -- Change "3" to however long you want the player to have to wait before they can get the tool again
				debounce = true
				hitPart.BrickColor = BrickColor.new("Bright green")
			end
		end
	end
end)
--[[
	
	Searches a dictionary for a value and returns the key for it
	
	Functions.SearchDictionary(
		table,					<-- |REQ| 	Dictionary to search through
		search,					<-- |REQ| 	Search value
	)
	
--]]





return function(dictionary, search)
	--- Scan dictionary
	for key, value in pairs(dictionary) do
		if value == search then
			--- Matching key!
			return key
		end
	end
	
	--- No matching value
	return
end
-- We want to be able to override outputFunction in tests, so the shape of this
-- module is kind of unconventional.
--
-- We fix it this weird shape in init.lua.


local loggerMiddleware = {
	outputFunction = print,
}

function loggerMiddleware.middleware(nextDispatch, store)
	return function(action)
		local result = nextDispatch(action)

		loggerMiddleware.outputFunction(("Action dispatched: %s\nState changed to: %s"):format(
			prettyPrint(action),
			prettyPrint(store:getState())
		))

		return result
	end
end

return loggerMiddleware
--Put this script in game.StarterPlayer.StarterCharacterScripts
--Put the punch animation id on the animation inside this script



local humanoid = script.Parent.Humanoid

local mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()
	if script.Parent:FindFirstChildOfClass("Tool") == nil and script.DamagePlayers.Debounce.Value == false then
		local punchTrack = humanoid:LoadAnimation(script.Animation)
		punchTrack:Play()
		script.RemoteEvent:FireServer()
		wait(script.Cooldown.Value)
		punchTrack:Stop()
	end
end)
--//Shifting//-


if key == "6" then
		 carSeat.Wheels.FR.Spring.Stiffness = 9000
 		 carSeat.Wheels.FL.Spring.Stiffness = 9000
elseif key == "5" then		 
	carSeat.Wheels.FR.Spring.Stiffness = 3500
	carSeat.Wheels.FL.Spring.Stiffness = 3500
	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