Jump to content

Could someone explain to me the proper use of "return"?


havenphillip
 Share

Recommended Posts

From Programming in Lua by Roberto Ierusalimschy 

 

A return statement returns occasional results from a function or simply finishes a function. There is an implicit return at the end of any function, so you do not need to use one if your function ends naturally, without returning any value.

For syntactic reasons, a break or return can appear only as the last statement of a block (in other words, as the last statement in your chunk or just before an end, an else, or an until). For instance, in the next example, break is the last statement of the then block.

    local i = 1
    while a[i] do
      if a[i] == v then break end
      i = i + 1
    end

Usually, these are the places where we use these statements, because any other statement following them is unreachable. Sometimes, however, it may be useful to write a return (or a break) in the middle of a block; for instance, if you are debugging a function and want to avoid its execution. In such cases, you can use an explicit do block around the statement:

    function foo ()
      return          --<< SYNTAX ERROR
      -- `return' is the last statement in the next block
      do return end   -- OK
      ...             -- statements not reached
    end
  • Like 1
Link to comment
Share on other sites

Ok. It's confusing. I have this at the bottom of my AI script. Do I need/can I make use of any returns anywhere? 

function Script:UpdateWorld()
    if self.enabled == true then
        self.despawnTimer = self.despawnTimer + Time:GetSpeed()/100
        if self.despawnTimer > self.despawnTime then
            self.mode = "dead"
            self:DespawnItem()
        end
    end

    if self.mode == "dead" then
        self.removeBodyTimer = self.removeBodyTimer + (Time:GetSpeed()/100)
        if (self.removeBodyTimer > self.removeBodyTime) then
            self:DespawnItem()
        end
    end
end

function Script:DespawnItem()
    self.entity:Hide()
    self.entity:Release()
end

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...