square brackets. The factorial function is implemented as a function in this example: function factorial(n) local x = 1 for i = 2, n do x = x * i end return x end Control flow Lua has one type of conditional test: if then end with optional else and elseif then execution control constructs. The generic if then end statement requires all three keywords: if condition then --statement body end The else keyword may be added with an accompanying statement block to control execution when the if condition evaluates to false: if condition then --statement body else --statement body end Execution may also be controlled according to multiple conditions using the elseif then keywords: if condition then --statement body elseif condition then --statement body else -- optional --optional default statement body end Lua has four types of conditional loops: the while loop, the repeat loop (similar to a do while loop), the numeric for loop, and the generic for loop. --condition = true while condition do --statements end repeat --statements until condition for i = first, last, delta do --delta may be negative, allowing the for loop to count down or up --statements --example: print(i) end The generic for loop: for key, value in pairs(_G) do print(key, value) end would iterate over the table _G using the standard iterator function pairs, until it returns nil. Loops can also be nested (put inside of another loop). local grid = { { 11, 12, 13 }, { 21, 22, 23 }, { 31, 32, 33 } } for y, row in pairs(grid) do for x, value in pairs(row) do print(x, y, value) end end Functions Lua's treatment of functions as first-class values is shown in the following example, where the print function's behavior is modified: do local oldprint = print -- Store current print function as oldprint function print(s) --[[ Redefine print function. The usual print function can still be used through oldprint. The new one has only one argument.]] oldprint(s == "foo" and "bar" or s) end end Any future calls to print will now be routed through the new function, and because of Lua's lexical scoping, the old print function will only be accessible by the new, modified print. Lua also supports closures, as demonstrated below: function addto(x) -- Return a new function that adds x to the argument return function(y) --[=[ When we refer to the variable x,