Quick overview
283
Before learning every feature in details, let's overview the basics of Lua syntax.
Variables
You don't need some special keyword to define a variable, you just define them right away, like you do in PHP for example. Also, you don't need to end the expression with some special token like semicolon:
name = "Sam"
email = "admin@samblog.com"
wallet = 100
You can define or reassign multiple variables in a single expression like that:
name, email = "Sam", "admin@samblog.com"
Control flow
if
statement:
if a > b then
print("a is greater than b")
end
while
statement:
while a < b do
a = next(a)
end
for
statement:
for i = 1, 10 do
print(i)
end
repeat-until
statement:
repeat
a = next(a)
until a >= b
Functions
Function example:
function add(a, b)
return a + b
end
print(add(10, 15))
Anonymous functions are supported as well:
function apply(value, fun)
return fun(value)
end
print(apply(15, function(value) return value * 10 end))
Arrays and tables
Defining an array:
primes = {2, 3, 5, 7, 11, 13}
print(primes[4])
Defining a table:
person =
{
name = "Sam",
email = "admin@samblog.com",
wallet = 100
}
print(person.name)
Comments
There are two types of comments in Lua:
-- This is a single-line comment
print("Foo")
--[[ This is
a multiline
comment --]]
print("Bar")
Alright, now you have a taste of basic Lua syntax constructions. Let's learn them one by one in details now.
Rate this post:
Lesson 2
Lesson 4
Share this page:
Learning plan
1. Introduction
What is Lua script and what are these tutorials about
The most simple Lua program and where you can run it
3. Quick overview
A very brief overview of Lua syntax and expressions
4. Data types
A list of data types and their descriptions which Lua operates on
5. Operators
A list of built-in operators in Lua
6. Control flow
A list of Lua statements which you use to organize control flow of a program