Tutorial by Examples

function add(a, b) return a + b end -- creates a function called add, which returns the sum of it's two arguments Let's look at the syntax. First, we see a function keyword. Well, that's pretty descriptive. Next we see the add identifier; the name. We then see the arguments (a, b) these c...
Functions are only useful if we can call them. To call a function the following syntax is used: print("Hello, World!") We're calling the print function. Using the argument "Hello, World". As is obvious, this will print Hello, World to the output stream. The returned value is ...
Creating anonymous functions Anonymous functions are just like regular Lua functions, except they do not have a name. doThrice(function() print("Hello!") end) As you can see, the function is not assigned to any name like print or add. To create an anonymous function, all you hav...
function sayHello(name) print("Hello, " .. name .. "!") end That function is a simple function, and it works well. But what would happen if we just called sayHello()? stdin:2: attempt to concatenate local 'name' (a nil value) stack traceback: stdin:2: in function ...
Functions in Lua can return multiple results. For example: function triple(x) return x, x, x end When calling a function, to save these values, you must use the following syntax: local a, b, c = triple(5) Which will result in a = b = c = 5 in this case. It is also possible to ignore r...
Variadic Arguments
local function A(name, age, hobby) print(name .. "is " .. age .. " years old and likes " .. hobby) end A("john", "eating", 23) --> prints 'john is eating years old and likes 23' -- oops, seems we got the order of the arguments wrong... -- this happ...
Some functions only work on a certain type of argument: function foo(tab) return tab.bar end --> returns nil if tab has no field bar, which is acceptable --> returns 'attempt to index a number value' if tab is, for example, 3 --> which is unacceptable function kungfoo(tab) ...
do local tab = {1, 2, 3} function closure() for key, value in ipairs(tab) do print(key, "I can still see you") end end closure() --> 1 I can still see you --> 2 I can still see you --> 3 I can still see you end ...

Page 1 of 1