Lua is a small, fast, general purpose scripting language designed for use in other applications.
Sample code[]
Hello World[]
Lua's Hello World can be achieved in one line of code:
print("Hello World!")
Comments[]
-- A comment in Lua starts with a double-hyphen and runs to the end of the line.
--[[ Multi-line strings & comments
are adorned with double square brackets. ]]
--[=[ Comments like this can have other --[[comments]] nested. ]=]
Loops[]
While loop:
local number = 0
while number < 10 do
print(number)
number = number + 1 -- Increase the value of the number by one.
end
Repeat ... until loop:
local number = 0
repeat
print(number)
number = number + 1
until number >= 10
For loop with step:
for number = 0, 9, 1 do
print(number)
end
for n = 1, 2, 0.1 do
print(n)
if n >= 1.5 then
break -- Terminate the loop instantly and do not repeat.
end
end
Functions[]
Normal function definition:
function factorial(n)
local x = 1
for i = 2, n do
x = x * i
end
return x
end
Functions can also be assigned to variables:
func = function(first_parameter, second_parameter, third_parameter)
-- insert function body here
Tables[]
Tables serve as a function of arrays normally found in other languages. Eements of a table can hold any value.
local array = {5, "text", {"more text", 463, "even more text"}, "more text"}
print(#array) --> 4 ; the # operator for strings can also be used for arrays, in which case it will return the number of values in the array
-- This example demonstrates how tables can be nested in other tables. Since tables themselves are values, tables can include other tables. Arrays of tables are called multi-dimensional arrays.
Further reading[]
- Official website
- Lua at Wikipedia
![]() |
This page uses content from Wikipedia. The original article was at Lua. The list of authors can be seen in the page history. As with the Programmer's Wiki, the text of Wikipedia is available under the GNU Free Documentation License. |