Lua syntax forms the backbone of writing efficient and readable code in the Lua programming language. Understanding these fundamental rules is crucial for developers of all levels.
Lua programs consist of a series of statements. Each statement typically occupies a single line, but you can use semicolons to separate multiple statements on one line.
print("Hello")
x = 5; y = 10; print(x + y)
In Lua, variables are dynamically typed. You don't need to declare their type explicitly. Assignment is straightforward:
name = "Alice"
age = 30
is_student = true
Lua uses the keyword local
to declare local variables. Without it, variables are global by default.
Lua supports single-line and multi-line comments:
-- This is a single-line comment
--[[
This is a
multi-line comment
]]
Lua provides several control structures for program flow:
if age >= 18 then
print("Adult")
elseif age >= 13 then
print("Teenager")
else
print("Child")
end
Lua offers various loop types, including while loops, for loops, and repeat-until loops.
-- While loop
while count > 0 do
print(count)
count = count - 1
end
-- Numeric for loop
for i = 1, 5 do
print(i)
end
-- Generic for loop
for key, value in pairs(table) do
print(key, value)
end
-- Repeat-until loop
repeat
input = io.read()
until input == "quit"
Functions in Lua are first-class values. They can be assigned to variables, passed as arguments, and returned from other functions.
function greet(name)
return "Hello, " .. name
end
print(greet("Bob"))
Tables are the primary data structure in Lua. They can be used as arrays, dictionaries, or a combination of both.
-- Table as an array
fruits = {"apple", "banana", "orange"}
-- Table as a dictionary
person = {name = "Charlie", age = 25}
-- Accessing table elements
print(fruits[2]) -- Output: banana
print(person.name) -- Output: Charlie
Mastering Lua syntax is the first step towards becoming proficient in Lua programming. As you progress, explore more advanced topics like object-oriented programming, coroutines, and modules to fully leverage Lua's capabilities.