Jump to content

[Help] Usage of "return"


ManeXi

Recommended Posts

These days I have been taking a look to script made by experienced scripters of MTA and one of main differences I see between them and me it's that they are continiously using "return", can anyone explain me what does and what's the point of using it?

for example in this useful function:

function getPedMaxHealth(ped) 
    assert(isElement(ped) and (getElementType(ped) == "ped" or getElementType(ped) == "player"), "Bad argument @ 'getPedMaxHealth' [Expected ped/player at argument 1, got " .. tostring(ped) .. "]") 
    local stat = getPedStat(ped, 24) 
    local maxhealth = 100 + (stat - 569) / 4.31 
    return math.max(1, maxhealth) 
end 

Link to comment
  • Discord Moderators

return is a keyword which stops the execution of a function and returns a value to the caller. It can only be used at the end of a block (if .. then .. end, function .. end, for .. do .. end, do .. end, while .. do .. end, repeat .. until); that is, it must be the last thing you write on it. If no value is specified, then the return value will be nil. Every function has an implicit return in the end of its block, so the following examples are exactly the same thing:

local function hey() 
    outputChatBox("Hello!") 
end 
  
outputChatBox( "The return value is: " .. tostring( hey() ) ) -- Will output nil 

local function hey() 
    outputChatBox("Hello!") 
    return 
end 
  
outputChatBox( "The return value is: " .. tostring( hey() ) ) -- Will output nil 

local function hey() 
    outputChatBox("Hello!") 
    return nil 
end 
  
outputChatBox( "The return value is: " .. tostring( hey() ) ) -- Will output nil 

This code shows a bit more advanced stuff with return:

local function hey() 
    outputChatBox("Hello!") 
    do 
        -- Exit the function here and return the string "Hello!" 
        return "Hello!" 
    end 
    outputChatBox("I will never be executed!") 
end 
  
outputChatBox( "The return value is: " .. tostring( hey() ) ) -- Will output "The return value is: Hello!" 

In the function you posted, return is used to give the caller a number containing the ped's max health, so he can use that value to proceed with the script:

pedMaxHealth = getPedMaxHealth(ped) 
  
-- Because getPedMaxHealth returns a number, the pedMaxHealth variable will contain the max HP of the desired ped, so it won't be nil 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...