Development Environment: MacOS
Lua 5.4.4
External Link: Runoob Tutorial - Lua
Introduction
Lua, named after the moon, is a very simple, fast, and powerful scripting language, known for being underestimated.
Basic Syntax
Lua is very simple, so simple that you can easily master it in an afternoon.
Hello World!
print("Hello World")
Comments
-- Single-line comment
--[[
Multi-line comment
--]]
Variables
By default, variables are always considered global.
Global variables do not need to be declared. Once a value is assigned to a variable, it creates the global variable. Accessing an uninitialized global variable will not cause an error, but the result will be: nil
—— Runoob Tutorial/Lua Basic Syntax
The local
keyword is used to set a local variable.
-- Global variable
variable = 123
-- Set local variable
local local_variable = "string"
-- Long variable
many_line_text = [[
/ _
(__(/(/
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
]]
Basic Types
Except for replacing NULL
with nil
, there is no difference. (Learn more).
-- Null
nil_variable = nil
print(nil_variable)
Variable Operations
Concatenating two variables#
-- Concatenating variables
local link_str_a = "astr"
local link_str_b = "bstr"
local str_c = link_str_a..link_str_b
print(str_c)
Type conversion#
-- Type conversion
local int_a = tostring(10)
print(type(int_a))
int_a = tonumber(int_a)
print(type(int_a))
Various ways to output variables in the command line#
-- Global variable
variable = 123
-- Set local variable
local local_variable = "string"
print("var = ", variable, "local var = ", local_variable)
print(string.format("var = %d, local var = %s", variable, local_variable))
Arrays and Indices
Note⚠️:
Lua arrays start counting from 1, not 0!!!
-- Arrays
array = {233, "qwq", 996, "乐"}
print(array[1])
-- Inserting
-- Insert at the end
table.insert(array, "Inserted new element")
-- Insert in the middle
table.insert(array, 2, "The second element has changed")
-- Insertion does not change the previous elements, the previous second element becomes the third
print(array[5]) -- Inserted new element
print(array[2]) -- The second element has changed
print(array[3]) -- qwq
-- Removing
-- Remove the second element
table.remove(array, 2)
print(array[2]) -- The second element has changed, the third element becomes the second
-- Assigning the removed element
local remove_number = table.remove(array, 1)
-- Now, remove_number = 233(array[1]), array[1] = "qwq"
print(array[1])
print(remove_number)
-- Indices
str_array = {
str_a = "a",
int_a = 123456,
-- Strange index
[";;,fun"] = "233"
}
print(str_array["str_a"])
-- or
print(str_array.int_a)
-- and
print(str_array[";;,fun"])
-- Assignment
str_array["abuc"] = "223"
print(array.abuc)
Functions and Conditions
-- Functions and if
function calculate(symbol, a, b)
-- In Lua, the not equal sign is represented by `~=`
--[[
`or` == `||`
`and` == `&&`
`not` == true -> false or false -> true
--]]
if ((type(symbol) ~= "string" or (type(a) or type(b)) ~= "number")) then
print("Error: Unknown input type")
return nil
end
if (symbol == "+") then
return a+b
elseif (symbol == "-") then
return a-b
elseif (symbol == "*") then
return a*b
elseif (symbol == "/") then
return a/b
else
print("Error: Unknown symbol type")
return nil
end
end
print(calculate("+", 1, 2))
Various Loops
-- Loops
while_var = 0
-- Check before the loop
while (while_var < 3) do
while_var = while_var + 1
end
print("while_var ->", while_var)
-- Check after the loop
repeat
while_var = while_var + 1
until (while_var > 5)
print("while_var ->", while_var)
-- i=3, i = i-1 each time until i==1
for i=3, 1, -1 do
print(i)
end
-- Generic for loop
for i, v in ipairs(array) do
print(i, v)
end
-- Lua supports nested loops
more_array = {}
for i=1, 3 do
more_array[i] = {}
for j=1, 3 do
more_array[i][j] = i*j
end
end
-- Accessing arrays
for i=1,3 do
for j=1,3 do
print(string.format("%d ", more_array[i][j]))
end
end
Multi-File Programming (Packages)
In Lua, we can easily call packages using require(package name)
. However, note that require
by default looks for package files in the project's root directory, not the working directory of the code file. If you put the package elsewhere, like this:
Project Directory
Code Directory (src)
main.lua
mod.lua
You need to tell require
where it is when calling it:
-- Look for the mod package in the src directory of the project
require(src.mod)
Example
Create mod.lua
in the same directory:
-- mod.lua
-- This is a package
mod = {}
mod.constant = "This is a constant"
mod.constant_two = "This is another constant"
-- This is a public function
function mod.add(a, b)
return a+b
end
-- This is a private function
local function subtraction(a, b)
return a-b
end
-- Call
function mod.open_sub(a, b)
subtraction(a, b)
end
return mod
Call in main.lua
:
-- Call the package
require("mod")
-- Use
print(mod.add(1, 2))
Miscellaneous
Getting the length of an array or variable#
-- Get the length
local local_variable = 123
array = {1, 2, 3, 4, 5}
-- Add `#`
print(#array)
print(#local_variable)