What does next() do in this block of code?

Is next() just used the same way I would set a variable here (does it have the same purpose of assigning a local variable called winner and referencing it)?

local function getWinner()
	local _, winner = next(Players:GetPlayers())
	for _, player in ipairs(Players:GetPlayers()) do
		if (player.leaderstats.Points.Value > winner.leaderstats.Points.Value) then
			winner = player
		end
	end
	return winner
end
2 Likes

To oversimplify, next takes either one or two arguments. It returns the first key/value pair in a table. If you give it a second argument, a valid key from the table, it will give you the first key/value pair after the one you specified. Behind the scenes, it is how for I,v in pairs works. He could also have done this, and it would have been shorter, cleaner, and faster.
local winner = Players:GetPlayers()[1]

1 Like

To clarify a little more, next exists so you can get k/v pairs in a dictionary, where the keys are named (and tab[1] doesn’t exist as a result)

Edit @LordIsaacofBargo

Here are some examples for anyone in the future that needs them.

local dictionary = {["car1"] = "Red", ["car2"] = "Green", ["truck1"] = "White"}
local list = {"Apple", "Orange", "Banana"}

-- Demonstration of lists vs dictionaries
print(list[1]) -- Apple
print(dictionary[1]) -- nil

-- Get the first result
print(next(dictionary)) -- car1, Red
print(next(list)) -- 1, Apple

-- Get the `next` result
print(next(dictionary, "car1")) -- car2, Green
print(next(list, 1)) -- 2, Orange

As a bonus, this is how pairs uses next behind the scenes.

local function pairsDuplicate(t)
    return next, t
end
for i, v in pairsDuplicate(someTable) do -- this works
for i, v in next, someTable do -- also works

Don’t worry too much about understanding why this works, as it’s very seldom used and I always forget the intricacies myself, but you can make your own functions that a loop can use. You can make, for example, this function.
for partName, part in GetBlueColoredParts(game.Workspace) do

21 Likes

People use it instead of pairs as a micro-optimization (that I think no longer even works in Luau?)

It’s generally not useful unless you’re iterating over a Table in a very tight loop where the micro-optimizations start to matter. If you don’t understand what that means, don’t use next, use pairs - it’s easier to read.

3 Likes

Hey, the code doesn’t work for me. Please help.

module.damage = {
	["10"] = 2500;
	["20"] = 5000;
	["30"] = 15000;
	["40"] = 35000;
	["50"] = 50000;
	["60"] = 75000;
	["70"] = 125000;
	["80"] = 300000;
	["90"] = 475000;
	["115"] = 750000;
	["135"] = 1050000;
	["175"] = 1350000;
	["225"] = 1850000;
	["275"] = "MAX";

}
	local nextIndex = nil
	print(next(module.damage, tostring(Data))) -- it prints nil twice

I tried your code and it seems to work, but the problem is in the tostring(Data). I don’t know what you are trying to do and if you just copied some code from your script. It would be nice if you could share the whole code so I can see where you are creating the Data variable from or else I can’t solve it.

Hello! Sorry, I wasn’t clear about that, but tostring(Data) is basically “10” so it should next(module.damage, tostring(Data)) should return “20”, 5000 but is doesn’t. I solved this btw, making my own function. THanks for replying tho

1 Like

My goal was to get a function to do this:

local nextKey, nextValue = myFunction(module.damage,"10")
--nextKey = "20"
--nextValue = "5000"

I already made that function by the way, but thanks for replying!

Why does

local dictionary = {
	["car1"] = {
		
	},
	["car2"] = {
		
	},
	["truck1"] = {
		
	}
}

print(next(dictionary))

print out “car1 {}”
but

local dictionary = {
	["new"] = {
		
	},
	["quick"] = {
		
	},
	["cya"] = {
		
	}
}

print(next(dictionary))

print out “car {}”?

Shouldn’t the piece of code that prints out “car {}” print “new {}” instead?

I’m really sorry to drag you back into this thread especially if you already gained more knowledge on this subject since then, but I wanted to make sure this was cleared up for future readers of this thread.
It doesn’t matter about the size of the loop, the pairs function is only called once. That means that no matter how many times it loops, it doesn’t get less efficient. So the micro-optimization is likely the most negligible micro-optimization I’ve ever seen. As far as that Luau bit, I had heard of them doing some optimizations for common things, though I’m not the guy to ask.

Let me start with some basics here just so that you and anyone reading it will understand.
There are two types of tables in Lua. They are lists/arrays and dictionaries/tables. In Lua the term “table” is ambiguous and can mean either so I tend not to use it.
Lists/arrays use indices or indexes depending on which you prefer to call them, and they are whole numbers which start at 1. These are both lists/arrays.
{"car", "truck", "bus"}
{[1]="car", [2]="truck", [3]="bus"}
Dictionaries use keys and they can be anything. Most commonly they are strings and they can be set up like this.
{car="red", truck ="white"}
["car"]="red", ["truck"]="white"}
Here are a couple of examples of non-string keys.
[game.Players.JarodOfOrbiter] = "admin"
[-16.725] = 10

Now for the actual answer here.
Dictionaries/tables do not have any order to them. No matter how you set them up, you can’t guarantee that they will be in the order you wanted. You will need to use arrays if you want a certain order.

You can use a system like this for sorting if you wish. The list I’ve called “index” can be sorted, and you can use that to maintain an order.

local dictionary = {
    key = "red",
    anotherKey = "fish",
    key3 = "blue",
    bob = "fish"
}
local index = {"key", "anotherKey", "key3", "bob"}


print(dictionary[index[1]]) --> red
print(dictionary[index[3]]) --> blue
print(dictionary["anotherKey"] -- fish, to prove you can still use it like a dictionary

-- Sort alphabetically
table.sort(index, function(a,b) return dictionary[a]<dictionary[b] end)

print("Sorted alphabetically:")
for _, key in ipairs(index) do
    print(dictionary[key])
end
3 Likes

the function next() is unpredictable as it does not give you the next key and index of a dictionary. I had this same problem and it is the same as pairs(). If you want to order the dictionary, you have to convert it into an array of dictionaries. But, if the keys of your dictionary are arranged in alphabetical order then it is possible to loop through it with table.sort().

1 Like

Thank you for the detailed answer! That sucks because I need to use a dictionary for my game but I guess I’ll just use arrays instead :slightly_smiling_face:

What is your dictionary for? I might be able to help you

1 Like

I was able to resolve it by changing it to an array instead, but thank you for wanting to help:)!