- Published on
The Basics of Lua Programming Language
- Authors
- Name
- Luiz Henrique Amaral Soares
What is Lua Language
Lua is a programming language created in 1993 in Brazil by a computer graphics group at PUC-RIO University. In the last 30 years, the language has gained a series of new features, such as object-oriented programming, functional programming, data-driven programming, and data description.
The Basic syntax
Comments
-- comment
print("Hello!") -- comment
--[[
multi-line
comment
]]--
Varibles
local a = 12 -- integer
local b = false -- boolean
local name = "luiz" -- string
Conditional Statements
-- Number Comparisons
local age = 10
if age > 18 then
print("You age are over 18")
end
-- elseif and else
age = 30
if age > 18 then
print("over 18")
elseif age == 18 then
print("18 yay!")
else
print("kiddo")
end
-- Booolean comparison
local Live = true
if Live then
print("Be Alive!")
end
-- String comparisons
local name = "Linus"
if name ~= "Linus" then
print("Not Linus")
end
Functions
local function print_number(num)
print(num)
end
-- or
local print_num = function(num)
print(num)
end
print_num(5) -- prints 5
-- multiple parameters
function sum(a, b)
return a + b
end
Loops
Different ways to make a loop:
While
local i = 1
while i <= 3 do
print("hello")
i = i + 1
end
For
for i = 1, 3 do
print("hello")
end
-- Both print "hello" 3 times
Tables
Tables are used to store complex data structures
Types of tables: arrays and dictionaries
Arrays
- Items can be accessed by "index"
local languages = {"lua", "c++", "python"} -- In Lua Arrays are start in 1 not in 0
print(languages[1]) -- lua
-- Different ways to loop through lists
for i = 1, #languages do
print(languages[i])
end
for index, value in ipairs(languages) do
print(languages[index])
-- or
print(value)
end
-- If you dont use index or value here then you can replace it with _
for _, value in ipairs(languages) do
print(value)
end
Dictionaries
- Dictionaries contains keys and values:
local data = {
name = "Mark",
age = 40,
isAlive = true
}
print(data["name"])
print(info.name)
-- Loop by pairs
for key,value in pairs(info) do
print(key .. " " .. tostring(value))
end
Conclusion
Lua Language is a very powerful language that provide lots of feature and better development experient