return

Functions in Lua can “return” at any given point.

Basics

The keyword “return” by itself just stops the function, ignoring any following code. It acts just the same as if it was the actual functions end.

Using “return”, you can skip remaining code under certain conditions, implement failsafes and cancel iterations at a special point.

Returning Values

This is where it gets interesting. “return” can be followed by any number of variable names and/or values.

The function above returns the string “a banana” every time it is called. That means where ever the function is being executed, the return values will be put.

The code above assigns the variable “my_banana” to the string “a banana”. Keep in mind that this requires the brackets ‘()’, with or without arguments. Else the variable references to the function and not the string.

Returning several variables is very simple:

 Using Return with Require

Another useful aspect of return is, that it can also be used at the end of a file. If that file is loaded using dofile or require (for example), the file will return the variables and values as if it was a function.

This is used in Don’t Starve: You can find it at the end of prefab-, component- and widget-files, and at the beginning of speech-files, to name a few.