I don't understand the use nor purpose of both "return" & "pairs", explanation appreciated

I’m learning scripting to the best of my own ability. I’m doing so through YouTube tutorials, which I know aren’t recommended by most, but I just don’t really know another way. I usually ask these questions to the Studio AI Assistant when something comes up in the video, but even it’s explanation wasn’t one I could fully understand.

The two things I don’t understand fully are return and pairs. Any help with this would be greatly appreciated. I know these are probably simple things to understand, but I’m not too fast of a learner.

2 Likes

return is used to get data from a function/module and pairs is for looping through arrays, but you don’t need to use that anymore. Now you can just do:

for key, value in array do
4 Likes

Does this also rule out ipairs() as unnecessary? From what understanding I have, pairs is random but ipairs() will read the array left to right, correct?

1 Like

return is used to, well, return a value from a function. This is very helpful for simplifying code that includes a lot of complex logic and needs to be repeated elsewhere, but the return result is needed. It’s typically applied to logic that can be applied to multiple situations. A basic example:

--we have the function 'getHalfBetweenNumbers'.
--This function gets the midpoint between two numbers.
local function getHalfBetweenNumbers(number1: number, number2: number): number
    --first, we get the result (assuming number2 is greater than number1)
    local diff = number2 - number1
    local result = number1 + diff

    --now we have the result of this, we need to return it to whatever called it
    return result
end

--so now, if we do this:
local midpoint = getHalfBetweenNumbers(5, 10)
--since that function returned 7.5, we now have 7.5 stored in the midpoint variable
print(midpoint) --> 7.5
2 Likes

ipairs() and pairs() essentially do the same thing but I think there is a slight different which you aren’t going to need to know. But yes, they are both unneeded for looping through an array.

2 Likes

pairs is a function that is helpful when iterating. It is not an iterator itself, but it’s a function that returns an iterator (an iterator loops over a table or dictionary).

pairs will include all the items within an iteration. This is used for things like dictionaries, where string keys or other data type keys are present.

local dict = {
    ["StringKey"] = 3
}

ipairs is an function that returns an iterator as well. It only includes numerical keys, e.g. keys that are a number or just a standard table.

local dict1 = {
    3,
    "hi",
    true
}

--or this format

local dict1 = {
    [1] = 3,
    [2] = "hi",
    [3] = true
}

--so if we did this:
local dict = {
    ["hi"] = 3,
    ["bye"] = 5
}

for _, item in ipairs(dict) do
    print(item) --nothing would output. There are no numerical keys in the table.
end

pairs is unneccessary because you can just use the for i, v in table syntax or next as an iterator.
next allows you to start from a specific point in the table when iterating, there’s basically no use for pairs in Luau now.

2 Likes

ipairs (short of index pairs) is used for array type tables, such as this one:

local myArray = {
    "This",
    "is",
    "an",
    "array",
    "!",
}

for index, value in ipairs(myArray) do
    print(index, value)
end

ipairs also gives the values in order from index 1 to #myArray (aka length of the array).

pairs on the other hand should be used for dictionary type tables, such as:

local myArray = {
    ["someKey"] = "wow",
    ["otherKey"] = "w0w"
}

for key, value in pairs(myArray) do
    print(key, value)
end

And yes, pairs isn’t as useful as ipairs, but it’s still good to know.

2 Likes

Dictionary iteration is pretty common; I’d say pairs is just as useful as ipairs. Either way, neither are necessary anymore since generalized iteration exists for Luau

2 Likes

Better iteration methods exist for dictionaries than pairs, I also ran some tests and pairs is significantly slower than ipairs, next, and no iterator syntax. All of these, including pairs, also work for numerical tables.

2 Likes

Functions normally return nothing, but we can tell them to do so. Using return is easy: when calling the function, simply set a new variable to the call, and that variable will become whatever we returned.

function MyFunction()
  print("I return nothing!")
end

function MyOtherFunction()
  print("I return 123")
  return 123
end

local my_variable = MyFunction() 
local my_other_variable = MyOtherFunction()

print(my_variable, my_other_variable) -- nil, 123

What can this be used for? Well, lots of things, but a simple example is if you want to make a function which takes numbers and adds them up together.

function AddNumbers(... : number) -- our input.
  local result = 0
  for index, value in {...} do
    result += value
  end
  return result
end

local my_addition = AddNumbers(2,3,1,5,6,1938,1,4)
print(my_addition) -- 1960

The …:number means we can have any amount of numbers as our input. We then loop over the values, and add them to the result, which we can then return.

1 Like

return returns a particular value from a function, for example

function add(a, b)
    return a + b
end

This function takes two numbers and adds them together, then returns the result. This allows you to write code like this:

local result = add(3, 4) -- result now equals 7

pairs is used when looping through a table with key/value pairs, such as

local fruit_costs = {Banana = 5.00, Apple = 2.50, Orange = 4.00}

As you can see, we have some keys (Banana, Apple, Orange) and each is associated with a value, 5.00, 2.50 and 4.00 respectively.

If this table was much longer, say it had 50 items, I could loop through it by using pairs() like so:

for fruit_name, cost in pairs(fruit_costs) do
    print(fruit_name .. " costs $" .. cost) -- prints out the cost of each fruit.
end

ipairs(), however, is used when you dont use key/value pairs but just use an array (i.e. a list of items).
For example, if I have a list of items in someone’s inventory, I would store them like this:

local inventory = {"Key", "Diamond", "Emerald", "Umbrella", "Ball", "Sandwich"}

If I wanted to loop through this list and print out all the items, I’d use ipairs()

for i, item in ipairs(inventory) do -- 'i' here represents the index of the item, which is the position in the list of the inventory
    print(item)
end

Hope this helps and feel free to mark it as a solution if it did :slight_smile:

3 Likes

I understand now, pairs & ipairs loop through arrays and dictionaries, but are no longer necessary because of table loops such as “for i, v in table do”

As I thought, return was simple and I’m just slow lol. I understand it now though, thanks to you all. Much appreciated!

2 Likes

This is true, but understanding the difference between an array/list and a dictionary is still very important. The reason why it’s called pairs and ipairs is because all tables contain pairs of a key and a value. So we loop through those pairs. Sometimes those keys are strings, or objects, or vectors. And other times they are indexed numerically. So if we type

local table = {false,true, 'hi', os.clock()}
for i,v in table do
print(i)
end
-- 1
-- 2
-- 3
-- 4

local table = {a=false,b=true, c='hi', d=os.clock()}
for i,v in table do
print(i)
end
-- a
-- d, out of order
-- c
-- b, out of order

The important thing to remember is you can’t index a dictionary, because they’re unsorted. So you may not get the same order of results every time, which explains why D and B are switched.

2 Likes

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