Functions


Functions in Lua are just values, like numbers or strings, and you can do with them anything you would with those. They are created by assigning them to variables, as follows: variable = function (arguments) body end.

Functions, like tables, are passed by reference, so if you assign a variable that has a function to another variable, both will be pointers to the same object.

A simple function:

> a= function() print ("hello") end
> a()
hello

Arguments

Functions can take any number of arguments. These are arguments are passed to function when it's called. Inside the function, the arguments look like variables, except they only exist inside the function.

Note: Until now, I only copied the code and output from "console" window of ESPlorer (right). In the next examples, to make things clearer and show code formating, I'll copy the code from the "code" window (left) and the output from the console window (right).

myfunc= function(a,b,c) 
    print (a) 
    print (b)
    print (c)
end
myfunc(7,33,"hello")


7
33
hello

Remember that variables in Lua are always global, unless specified otherwise.

Code:

myfunc= function(a, b, c) 
    x= a * 2 
    y= b * 2
    z= c * 2
end
myfunc(7,33,32)
print (x, y, z)


14    66    64

Returning values

Functions can return values using the command return followed by these values.

myfunc= function() 
    return "cat", "dog", "rat"
end

print(myfunc())


cat    dog    rat

Note: The command return in conjunction with conditional statements is used to exit a function.

myfunc= function() 
    print("one")
    print("two")
    if 3>2 then return end
    print("three")
end
myfunc()


one
two

results matching ""

    No results matching ""