Table of contents
Comments
-- Single line comment
--[[
Multi
line
comments
--]]
Display info
print('Hello world!')
-- or
print'Hello world!'
Types
There are eight basic types: nil, boolean, number, string, userdata, function, thread, and table.
To check type we can use
print(type("Hello world")) -- string
print(type(7)) -- number
print(type(print)) -- function
print(type(false)) -- boolean
print(type(nil)) -- nil
it returns string:
print(type(type(7)) == 'string') -- true
tostring and tonumber
local number = 10
local strNum = tostring(num);
print(type(strNum)) -- string
local stringNumber = "10"
local num = tonumber(stringNumber)
print(type(num)) -- number
Variables
Variable declaration
a = 10 -- global variable
local b = 20 -- local variable
Variable scope
if true then
e = 40
-- Unlike global variables, local variables have their scope
-- limited to the block where they are declared
local d = 30
end
print(e) -- 40
print(d) -- nil
String
Single-line string
local single_quote_string = 'Hello'
local double_quote_string = "World"
Multi-line string
local multi_line_string = [[
This
multi-
line
string
]]
Logical Operators
and
print(4 and 5) --> 5
print(nil and 13) --> nil
print(false and 13) --> false
or
print(4 or 5) --> 4
print(false or 5) --> 5
not
print(not nil) --> true
print(not false) --> true
print(not 0) --> false
print(not not nil) --> false
Conditionals
if then else
local value = 20
if value == 30 then
print("Value is 30")
elseif value == 40 then
print("Value is 40")
else
print("Value is not 30 or 40, but " .. value)
end
Invert value
local isLoggedIn = false
if not isLoggedIn then
print("Please log in!")
end
Loops
for loop
for i = 1, 100 do
print('i is: ' .. i)
end
while loop
local num = 0
while num < 50 do
print("num is: " .. num)
num = num + 1
end
repeat loop
local num = 10;
repeat
print("num is: " .. num)
num = num - 1
until num == 0
Functions
Function with return statement
local function add(a, b)
return a + b
end
local res = add(2, 2)
print(res) -- 4
Returning multiple results
local function nums()
return 7, 3, 1
end
local x, y, z = nums()
print(x, y, z) --- 7 3 1
Passing function to function
local fnArgs = function (fn, arg)
fn(arg)
end
fnArgs(print, 'Hello world!')
Closures and anonymous functions
local function adder(x)
return function (y) return x + y end
end
local res1 = adder(7)
local res2 = adder(15)
print(res1(12)) -- 19
print(res2(18)) -- 33
Vararg
local function add(...)
local res = 0
local vararg = {...}
for _,v in pairs(vararg) do
res = res + v
end
return res
end
print(add(1, 2, 3, 4, 5))
Tables
Define properties
local user = { first_name = 'Oleh' } -- Option 1: set the properties
user.second_name = 'Baranovskyi' -- Option 2: set the properties
print(user.first_name .. ' ' .. user.second_name) -- Oleh Baranovskyi
for key, val in pairs(user) do -- Iterate over the keys
print(key, val)
end
local dynamic_key = 'name'
local animal = { [dynamic_key] = 'Pluto' } -- Dynamic key
print(animal.name) -- Pluto
Remove properties
user.second_name = nil
print(user.second_name)
Using table as a list
local animals = { 'dog', 'cat', 'horse', 'pig', 'frog' }
for i = 1, #animals do -- #animals is the size of list
print(animals[i])
end
table.insert and table.remove
local printTable = function (t)
print('{' .. table.concat(t, ", ") .. '}')
end
local animals = { 'dog', 'cat', 'horse', 'pig', 'frog' }
table.insert(animals, 'bird')
printTable(animals) -- {dog, cat, horse, pig, frog, bird}
table.insert(animals, 1, 'duck')
printTable(animals) -- {duck, dog, cat, horse, pig, frog, bird}
table.remove(animals, 1)
printTable(animals) -- {dog, cat, horse, pig, frog, bird}
Print properties with penlight
local pretty = require('pl.pretty')
local t = {
username = 'obaranvoskyi',
name = {
first_name = 'Oleh',
secondname = 'Baranovskyi',
}
}
pretty.dump(t)
output:
{
name = {
first_name = "Oleh",
secondname = "Baranovskyi"
},
username = "obaranvoskyi"
}
Modules
Base module
hello.lua:
local M = {}
function M.hello(name)
print('Hello, ' .. name)
end
return M
main.lua:
local m = require('hello')
m.hello('Oleh')
Classes
Define class
Person = { name = '' }
function Person:new (o, name)
o = o or {}
setmetatable(o, self)
self.__index = self
self.name = name
return o
end
function Person:hello()
print('[Person] Hello, my name is ' .. self.name)
end
local person = Person:new(nil, 'Oleh')
person:hello()
Inheritance
Person = { name = '' }
function Person:new (o, name)
o = o or {}
setmetatable(o, self)
self.__index = self
self.name = name
return o
end
function Person:hello()
print('[Person] Hello, my name is ' .. self.name)
end
local person = Person:new(nil, 'Oleh')
person:hello()
Developer = Person:new()
function Developer:new (o, name, language)
o = o or Person:new(o, name)
setmetatable(o, self)
self.__index = self
self.language = language
return o
end
-- We override `hello` method for Developer
function Developer:hello()
print('[Developer] Hello, my name is ' .. self.name)
print('[Developer] I code on ' .. self.language)
end
local developer = Developer:new(nil, 'John', 'lua')
developer:hello()
LuaRocks
LuaRocks is the package manager for Lua modules.
Here is the list of supported commands:
for instance to install rock (module) with name
luarocks install penlight
or to open documentation:
luarocks doc penlight
show rock info:
luarocks show penlight
show installed rocks:
lurocks list
to remove:
luarocks remove penlight
to setup project folder (including local dependency management):
luarocks init