Background Info
Lua is elegant, it uses Mechanisms over Policies, It is designed to be embedded and It is COOOOOLLLL.
Comments
-- This is a comment, starts with two dashes
-- [[ This is
also a comment.
But it spans multiple lines!
--]]
Variables: Simple Literals
local number = 5
local string = "hello, world"
local single = 'also works'
local crazy = [[ This is
multi line and literal
]]
local truth, lies = true, false
local nothing = nil
Variables: Functions
local function hello(name)
print("Hello!", name)
end
local greet = function(name)
-- .. is string concatenation
print("Greetings, ".. name .. "!")
end
local higher_order = function(value)
return function(another)
return value + another
end
end
local add_one = higher_order(1)
print("add_one(2) -->", add_one(2))
-- Additional stuff related to function
local returns_four_value = function()
return 1, 2, 3, 4
end
first, second, third = returns_four_value()
-- Multiple returns
local variable_arguments = function(...) {
local arguments = { ... }
for i, v in ipairs({...}) do print(i, v) end
return unpack(arguments)
}
print(variable_arguments("hello", "world", "!"))
-- Function calling
local single_string function(s)
return s .." - WOW!"
end
local x = single_string("HI")
local y = single_string "HI" -- both works fine
local setup = function(opts)
if opts.default == nil then
opts.default = 17
end
print(opts.default, opts.other)
end
setup {other = true}
Variables: Tables
Effectively, Lua's only data structures. Same structure is used for maps & lists.
-- As a list...
local list = { "first", 2, false, function() print("Forth!") end }
print("Yup, 1-indexed: ", list[1])
print("Forth is 4...: ", list[4]())
-- As a dictionary...
local t = {
literal_key = "a string",
["an expression"] = "also works",
[function() end] = true
}
print("literal key: ", t.literal_key)
print("an expression: ", t["an expression"])
Control Flow
for loop
local favorite_anime = ["Naruto", "Gintama", "Haikyuu", "Boruto"]
-- for loop 1
for index = 1, #favorite_anime do
print(index, favorite_anime[index])
end
-- for loop 2
for index, value in ipairs(favorite_anime) do
print(index, value)
end
-- for loop of objects
local reading_scores = { shubham = 9.5, rohit = "N/A" }
for key, value in pairs(reading_score) do
print(key, value)
end
if statement
if loves_anime then
print("Read Naruto - it's cool")
else
print("Still Read Naruto - it's cool")
end
-- `nil` and `false` are only "falsy" value
-- Everything else is "truthy"
foo(true)
foo(0)
foo({}) -- All true
Modules
There isn't special about modules. They are just files which return something (mostly a table)
-- foo.lua
local M = {}
M.cool_function = function() end
return M
-- bar.lua
local foo = require("foo")
foo.cool_function()
