Explora Libros electrónicos
Categorías
Explora Audiolibros
Categorías
Explora Revistas
Categorías
Explora Documentos
Categorías
Comentarios:
--[[ This is
a multi-line
comment ]]
local str2 = [[
multi-line
string]]
Variables globales:
score = 0
If-then-else:
local x = 2
if x > 1 then
else
end
Mientras bucle:
local n = 5
while n > 0 do
print (n)
n = n - 1
end
-- prints 5 4 3 2 1
Repetir-hasta el bucle:
local n = 0
repeat
n = n + 1
print (n)
until n == 5
-- prints 1 2 3 4 5
En bucle:
for i = 1, 5 do
print (i)
end
-- prints 1 2 3 4 5
for j = 10, 1, -2 do
print (j)
end
-- prints 10 8 6 4 2
Puede salir de un bucle utilizando la breakdeclaración:
for j = 1, 10 do
print (j)
if j == 5 then
break
end
end
-- prints 1 2 3 4 5
Operadores:
Mesas:
t ["score"] = 10
t [1] = "foo"
t [true] = "x"
t .score = 10
print (t.score)
for i = 1, #arr do
print (arr[i])
end
-- prints 3, 4, 5
local t = {a = 1, b = 2, c = 3}
for k, v in pairs(t) do
print (k..":"..v)
end
for k, v in ipairs(arr) do
print (k..":"..v)
end
Funciones:
function factorial(n)
if n <= 1 then
return 1
else
return n * factorial(n-1)
end
end
return a + b
end
local t = {}
function t.say_hello()
print("hello")
end
Esto es equivalente a:
local t = {}
t .say_hello = function()
print("hello")
end
El código:
function t:f()
...
end
es equivalente a:
function t.f(self)
...
end
y el código:
t:f ()
es equivalente a:
t .f(t)
Por ejemplo:
local t = {x = 3}
function t:print_x()
print (self.x)
end
t:print_x () -- prints 3
t .x = 4
t:print_x () -- prints 4
local
function append_z(str)
return str.."z"
end
local
function sum(values)
local total = 0
for _, value in ipairs(values) do
end
return total
end
function f()
return 1, 2
end
local x, y = f()
print (x + y) -- prints 3