What to use pairs for?

I recently discovered you can use pairs to do something like this:

local a = pairs({"a","b","c"})
print(a({-1}))

But this doesn’t really seem to do anything or be useful for anything as it just prints whatever i put as the first value in the table (-1 in this case).

Is there any use for pairs in this specific way?

There’s a documentation page about the pairs() function. I think it explains well.

i am aware of this documentation page but it does not list the use of the example i listed above

1 Like

There’s not really any reason to use pairs directly (or at all, you don’t need it to loop over tables anymore).

You can use next to do something similar: next({ "a", "b", "c" }) will return 1, "a", and next({ a = "b" }) will return "a", "b". This is useful for checking if a table is empty.

1 Like

Adding on to @Dogekidd2012’s post, if you want to get the previous item in a table, you can use a simple method:

local table1 = {
	"Apples",
	"Oranges",
	"Bananas"
}

local nextindex, nextvalue = next(table1, 1) --nextindex = 2, nextvalue = "Oranges"

local function previous(array, index)
	return table.find(array, array[index - 1]), array[index - 1]
end

local previousindex, previousvalue = previous(table1, 2) --previousindex = 1, previousvalue = "Apples"

I prefer to be explicit in my iteration. I will use pairs for dictionary-like tables and ipairs for array-like tables.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.