邱 璇洛 (ゝ∀・)

邱 璇洛 (ゝ∀・)

你好哇(*゚∀゚*)~这里是邱璇洛的博客,常常用来记录一些技术文章和小日常~(σ゚∀゚)σ
twitter
tg_channel

Lua Introduction

Development Environment: MacOS
Lua 5.4.4
External Link: Lua Tutorial for Beginners

Introduction#

Lua, named after the moon, is a very simple, fast, and powerful scripting language, known for being underestimated.

Basic Syntax#

Lua is so simple that you can easily master it in just 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. After assigning a value to a variable, the global variable is created. 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.

-- Nil
nil_variable = nil
print(nil_variable)

Manipulating Variables#

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 on 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 Indexes#

Note⚠️: Lua arrays start counting from 1, not 0!!!

-- Arrays
array = {233, "qwq", 996, "乐"}
print(array[1])
-- Insertion
-- 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
-- Removal
-- Remove the second element
table.remove(array, 2)
print(array[2]) -- The second element has changed, the third element becomes the second
-- Assign the removed element to a variable
local remove_number = table.remove(array, 1)
-- At this point, remove_number = 233(array[1]), array[1] = "qwq"
print(array[1])
print(remove_number)

-- Indexes
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, `~=` is used for inequality
    --[[
        `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, such as 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 it in main.lua

-- Call the package
require("mod")
-- Use it
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)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.