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.
Before we explain more, let's cover some basic rules for naming variables in Lua:
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}
Variables in Lua have scope, which defines where they can be accessed. There are mainly two types of scope in Lua:
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)
Now that we understand the basics, let's see how we can use variables in Lua scripts. Here are some common scenarios:
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
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
local greeting = "Hello" local name = "Alice" -- Concatenation local message = greeting .. ", " .. name .. "!" print(message) -- prints: Hello, Alice!