Table of Contents

Lua variables

Welcome, if you want to understand scripts, its crucial to have a solid understanding of variables in Lua. Variables serve as containers for storing data that your script can manipulate, think of them as boxes with names, they can contain numebers, word, etc. Lua variables, covering their types, scope, and usage.

Naming rules

Before we explain more, let's cover some basic rules for naming variables in Lua:

Variable types

Declaring variables

In Lua, you don't need to explicitly declare the type of a variable. You can simply assign a value to a variable, and Lua will determine its type. Here's how you declare variables:

-- Number variable
local age = 25

-- String variable
local playerName = "John"

-- Boolean variable
local isOnline = true

-- Table variable
local playerData = {name = "Alice", score = 100}

-- Another form of Table variable
local playerIds = {1583,2229}

Variable scope

Variables in Lua have scope, which defines where they can be accessed. There are mainly two types of scope in Lua:

  1. Global Scope: Variables declared outside of any block or function have global scope and can be accessed from anywhere in the script.
  2. Local Scope: Variables declared within a block or function have local scope and are only accessible within that block or function.

In Lua, a block is a group of instructions or commands that are grouped together. They are enclosed within keywords such as “do”, “then”, or inside a function and finish with “end”. Blocks help organize code and make it easier to manage. When Lua runs, it executes each instruction in the block sequentially, one after the other.

-- Global variable
globalVar = 10

-- Function defining a local variable
local function myFunction()

	-- localvar can't be accesed outside this block, in this case the function
	local localVar = 20
	print(localVar) -- Will print 20
end

-- Accessing global variable: will print 10
print(globalVar)

-- Accessing local variable outside of the block its in: will give us nil (nothing)
print(localVar)

Variable usage

Now that we understand the basics, let's see how we can use variables in Lua scripts. Here are some common scenarios:

Using them in code

playerName = "NotSoPr17"
uid = 75820841
uses_lua = true

print(playerName)

if uid >= 0 then 

    print("uid: ".. uid)

end

if uses_lua == true then 
    print("Player uses lua")
else
    print("Player doesn't use lua")
end

Arithmetic Operations

local num1 = 10
local num2 = 5

-- Addition
local sum = num1 + num2

-- Subtraction
local difference = num1 - num2

-- Multiplication
local product = num1 * num2

-- Division
local quotient = num1 / num2

-- Modulus (Remainder after division)
local remainder = num1 % num2

String Manipulation

local greeting = "Hello"
local name = "Alice"

-- Concatenation
local message = greeting .. ", " .. name .. "!"

print(message) -- prints: Hello, Alice!