A for embedded use in applications. It has a C API and so interfaces with other languages easily. Lua is cross-platform, since the interpreter is written in ANSI C.
Comments start with -- rather than the more common //. Multi-line comments... or strings... are delineated with double square brackets. e.g. [[ this is a comment/string ]]
Each statement must be on it's own line. There are no ';' or other terminators. Intenting is not required (not Python)
All functions are anonymous. The syntax:
function add (x, y) return x + y end
is just syntactic sugar for an assignment of an anonymous function to a variable
add = function (x, y) return x + y end
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:
function addto(x) -- Return a new function that adds x to the argument return function(y) --[=[ When we refer to the variable x, which is outside the current scope and whose lifetime would be shorter than that of this anonymous function, Lua creates a closure.]=] return x + y end end fourplus = addto(4) print(fourplus(3)) -- Prints 7 --This can also be achieved by calling the function in the following way: print(addto(4)(3)) --[[ This is because we are calling the returned function from 'addto(4)' with the argument '3' directly. This also helps to reduce data cost and up performance if being called iteratively. ]]
A new closure for the variable x is created every time addto is called, so that each new anonymous function returned will always access its own x parameter. The closure is managed by Lua's garbage collector, just like any other object.
Lua has four types of 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.
You can also do a nested loop, which is a loop inside of another loop.
local objects = { "hello", "hi" } for i,v in pairs(_G) do for index,value in pairs(object) do print(objects[i]) print(value) end end
See also: