๐ŸŒ‘Lua

Introduction to Lua

What is Lua?

Lua is a lightweight, high-level, multi-paradigm programming language designed primarily for embedded systems and clients. It was designed and implemented by a team at the Pontifical Catholic University of Rio de Janeiro, Brazil, in 1993.

Features of Lua

  • Simple and easy to learn syntax

  • Dynamic typing and garbage collection

  • Can be used as an extension language for other programs

  • Supports procedural, object-oriented, and functional programming styles

Fundamentals of Lua

Variables

In Lua, variables do not need to be declared with a specific type, and the type can change during runtime. To assign a value to a variable, use the = operator.

x = 10
x = "hello"

Data Types

Lua supports 8 basic data types: nil, boolean, number, string, function, userdata, thread, and table.

Operators

Lua supports various operators such as arithmetic +, -, *, /, % (modulus), comparison ==, ~= (not equal), <, >, <=, >=, and logical and, or, not.

Conditional Statements

Conditional statements in Lua are similar to other programming languages and use the keywords if, then, elseif, and else.

if x > 0 then
  print("x is positive")
elseif x < 0 then
  print("x is negative")
else
  print("x is zero")
end

Loops

Lua supports two looping structures: for and while.

-- for loop
for i = 1, 10 do
  print(i)
end

-- while loop
local i = 1
while i <= 10 do
  print(i)
  i = i + 1
end

Functions

Functions in Lua can be declared using the function keyword and can return multiple values. Functions can be assigned to variables and passed as arguments to other functions.

-- Function with no arguments
function printHello()
  print("Hello")
end

-- Function with arguments
function sum(a, b)
  return a + b
end

-- Function as a variable
local add = function(a, b) return a + b end

Tables

Tables in Lua are associative arrays and can be used as arrays, dictionaries, records, etc. They are defined using curly braces {}.

-- Array
local array = {1, 2, 3, 4, 5}

-- Dictionary
local dict = {key1 = "value1", key2 = "value2"}

-- Record
local record = {name = "John", age = 30, salary = 5000}

These are some of the basics of the Lua programming language. Hope this helps you get started!l

Last updated