How do I get the lowest value from a table with custom indexes?

I am trying to get the distances between two walls, and I need to have those indexes so I can fire a function from a module, with the same name as the index. So I’ve seen this topic but it gave me the error 15:40:46.886 - Players.zamd157.PlayerGui.LocalScript:20: missing argument #1 to ‘min’ (number expected), so I’ve removed the indexes so they are default 1, 2 and run the code, and it worked. Hovewer as stated above I need to have those indexes, so I’d be grateful for someone to appoint the mistake. Script:

local uis = game:GetService("UserInputService")
local rs = game.ReplicatedStorage

local modules = rs.modules

local player = game.Players.LocalPlayer
local char = player.Character

local smallestDistance

local taskModule = require(modules.eTasksHandler)

	if gpe then return end
	local distance = {
		test0 = (char.PrimaryPart.Position - game.Workspace.BackWall.Position).magnitude,
		test1 = (char.PrimaryPart.Position - game.Workspace.RightWall.Position).magnitude
	smallestDistance = math.min(table.unpack(distance))


Any help is appreciated!

For starters the entire table library is irrelevant to dictionaries so don’t bother with that (calling table.unpack on the dictionary in your case would’ve returned nil and that’s what you passed to the function math.min - causing your error, since nil isn’t a valid argument to math.min when used alone (or as the first argument as well))

math.min will return the least of the values passed to it, so take care of the above and just compare the magnitudes.

Instead of calling table.unpack on a dictionary try assigning variables to your numbers, or if there’s an unknown amount of values try using some form of iteration, and in the end compare the magnitudes by calling math.min passing the tuple number of arguments (either pass each one explicitly or pass the tuple amount of values by calling table.unpack on an array containing the magnitudes whatever’s relevant to your usecase).

if when you did char.PrimaryPart you meant the HumanoidRootPart, this will do what you want

local uis = game:GetService("UserInputService")
local rs = game:GetService("ReplicatedStorage")

local modules = rs:WaitForChild("modules")

local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()

local primaryPart = char:WaitForChild("HumanoidRootPart")

local walls = {
	test0 = workspace:WaitForChild("BackWall"),
	test1 = workspace:WaitForChild("RightWall"),

local taskModule = require(modules:WaitForChild("eTasksHandler"))

uis.InputBegan:Connect(function(keyCode, gpe)
	if gpe then return end
	local distances = {}
	for key, wallInstance in pairs(walls) do
		table.insert(distances, {(primaryPart.Position - wallInstance.Position).Magnitude, key})
	table.sort(distances, function(x, y)
		return x[1] < y[1]
1 Like