I was just reading up on things and I was looking into the return statement, and I understand for the most part what it does but I wanted to know in what cases this would be helpful?
Q:
Where would the return statement be applicable?
The return statement can be used to feed data from a different operation or function.
For example, dictionaries are made using hashmaps so they cannot be measured like normal arrays.
local myDict = {["John"] = 17, ["Jane"] = 18} local myTab = {"John", "Jane"} print(#myTab) -- prints the length of myTab, which is 2. print(#myDict) -- returns an error, either 0 or nil.
In this case, to measure the length of the dictionary I'm going to use a function.
function findLength(table) local counter = 0 for i, v in pairs(Table) do counter = counter + 1 end -- Now that the loop has finished, send the total return counter end print("My dictionary is "..findLength(myTab).." elements long.") -- This would print that the dictionary is 2 elements long
Below is a function that I have used in the past to determine the security level on a player's keycard shortly after spawning. I call assignClearance from within a function which writes on the side of a handheld tool.
function assignClearance(player, groupId) player:GetRankInGroup(groupId) if player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) == 255) then return 6 elseif player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) >= 250) then return 5 elseif player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) >= 248) then return 4 elseif player:IsInGroup(GroupID) and (player:GetRoleInGroup(GroupID) == "Under Investigation") then return 0 elseif player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) == 3) then return 3 elseif player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) == 2) then return 2 elseif player:IsInGroup(GroupID) and (player:GetRankInGroup(GroupID) == 1) then return 1 else return 0 end end
In short, the return statement helps you keep your code more robust and reusable as it often saves you from having to repeat blocks of code over again.
Below are a few examples of what to use it for:
Remote Functions can use the return statement to give information back to the side of the game which Invoked it.
Module Scripts require you to return the table created at the beginning of the script
Local Functions can return information you need or calculated to wherever they were called from
You can also use returns to break out of multiple loops at once