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 