Return statement in Lua Programming

LuaServer Side ProgrammingProgramming

There are certain cases where we want to return a value from a given function so that we can use it later. These return values make use of a return keyword which in turn allows a function to return values.

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.

It should be noted that the return statement is optional; if not specified, the function returns nil.

Also, only one return statement is allowed in a function.

Syntax

return expression/value

Now let’s consider an example where we would like to return a value from a function and then use that value and print it.

Example

Consider the example shown below −

function bar()
   return 2 * 10
end

x = bar()
print(x)

Output

20

The above example is the most common use-case of return statements. Let’s consider one more example of return statement in Lua.

Example

Consider the example shown below −

local v = 16
function foo()
   if v == 16 then
      return
   end
   print("foo")
end
print("Completed")

Output

Completed
raja
Published on 01-Dec-2021 10:44:34

Advertisements