Table of contents
0. Install
0.1 install
mac:
brew install lua
0.2 Test run
vi test.lua
print("Hello World!")
lua test.lua
Or specify the interpreter to execute
#!/usr/local/bin/lua
print("Hello World!")
1. Variables
1.1 Variable type
There are 8 basic types in Lua: nil, boolean, number, string, userdata, function, thread and table
a=10
a=2.5
a="abcd"
Userdata is a user-defined data used to represent a type created by an application or a C/C++ language library, which can store data of any C/C++ data type (usually struct and pointer) to Lua variable call.
1.2 Variable names
Letters, numbers, underscores (cannot start with a number)
1.3 Scope
Local variable: local flag
function num()
local i = 1
j = 2
print(i)
print(j)
end
num()
print(i)
print(j)
output result
1
2
nil
2
1.4 Data type conversion
tostring()
tonumber()
a=100
b=tostring(a)
print(a,' ',b)
print(type(a),' ',type(b))
c='200'
d=tonumber(c)
print(c,' ',d)
print(type(c),' ',type(d))
1.5 Delete global variables
assign nil
a=10
a=nil
-- nil 作比较时应该加上双引号
type(X)=="nil"
2. Operator
2.1 Arithmetic operators
+ - * / % ^
2.2 Relational Operators
== ~= > < >= <=
2.3 Logical operators
and or not
2.4 Concatenation Operators
..
a=1
b=2
c=a..b
print(c)
2.5 Unary operators
get string length#
print(#'hello world')
3. String
3.1 Statement
a='hello'
b="hello"
c=[['hello']]
d=[["hello"]]
print(a)
print(b)
print(c)
print(d)
3.2 Common methods
-- 转大写
a='hello'
print(string.upper(a))
-- 转小写
b='HELLO'
print(string.lower(b))
-- 替换
-- 参数 要被替换的字符串,指定替换前的字符,指定替换后的字符,指定替换次数,如果不指定替换次数则全部替换
local c=string.gsub("hello","l","hh",1)
print(c)
-- 查找位置 查找第一个出现在指定字符串中字符的位置,找不到的话就返回nil
-- 参数 目标字符串,目标字符,开始位置
local d=string.find("hello","l",5)
print(d)
-- 反转
local e=string.reverse('hello world')
print(e)
-- 字符串长度
local f=string.len("hello world")
print(f)
-- 字符串拷贝
local g=string.rep("hello",2)
print(g)
-- 字符串截取
local h=string.sub("hello",2,3)
print(h)
-- 字符串格式化
local i=string.format("the value is:%d",i)
print(i)
4. Process control
4.1 if
-- if
a=200
if (a>1000)
then
print('more than 1000')
else
print('less than 1000')
end
-- if-else
a=200
if (a>1000)
then
print('more than 1000')
elseif (a>1500)
then
print('more than 1500')
else
print('that')
end
4.2 for loop bad
-- 从10开始,每次-2,直到值等于4
for a=10,4,-2 do
print(a)
end
-- 从1开始,每次+2,直到值等于10
for a=1,10,2 do
print(a)
end
4.3 while loop
a=1
while (a<10)
do
a=a+1
print(a)
end
4.4 repeat…until
a=1
repeat
a=a+1
print(a)
until(a>5)
4.5 break
a=1
while(a<10)
do
print(a)
a=a+1
if(a>5)
then
break
end
end
4.6 goto
Label format::: Label ::
local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- a 小于 3 的时候跳转到标签 label
end
-- 利用goto实现continue
for i=1, 3 do
if i <= 2 then
print(i, "yes continue")
goto continue
end
print(i, " no continue")
::continue::
print([[i'm end]])
end
5. Function
5.1 Definition
function 函数名(参数)
函数内容
return 返回值 --可以没有
end
5.2 No-argument functions
function hello()
print('hello world')
end
hello()
5.3 Functions with parameters
function hello(a,b)
print(a+b)
end
hello(2,3)
-- 可变参数
function add(...)
local s = 0
for i, v in ipairs{
...} do -- {...} 表示一个由所有变长参数构成的数组
s = s + v
end
return s
end
print(add(3,4,5,6,7))
5.4 Return value
-- 单个返回值
function hello(a,b)
return a+b
end
print(hello(2,3))
-- 多个返回值
function hello(a,b)
return a+b,a*b
end
print(hello(2,3))
5.5 Anonymous functions
function fun(num)
print("num:",num)
num=num+1
return function(x)
print("x:",x)
print("x*num",x*num)
end
end
fun(12)(10)
5.6 Closure function
A closure is a variable that uses an internal function to call an external function. Generally, the internal function is returned and then the external function is used to call it.
function fun()
local num=10
function ff()
num=num+1
print(num)
end
return ff
end
fun()()
5.7 Recursion
function ff(num)
if(num==0 or num==1)
then
return 1
else
return ff(num-1)*num
end
end
print(ff(5))
6、table
[The default initial index of a table in Lua generally starts with 1]
6.1 Arrays
6.1.1 One-dimensional arrays
can grow dynamically
arr={}
arr[1]=123
arr[2]=342
print(arr[1])
6.1.2 Multidimensional arrays
arr={
}
for a=1,4 do
arr[a]={
}
for b=1,4 do
arr[a][b]=a+b
end
end
for a=1,3 do
for b=1,3 do
print(a,":",b," ",arr[a][b])
end
end
-- 组合写法
arr={
}
local n1,n2=3,4
for i=1,n1 do
for j=1,n2 do
arr[i*n1+n2]=10
end
end
for a=1,n1 do
for b=1,n2 do
print(a,":",b," ",arr[a*n1+n2])
end
end
6.1.3 Release memory space
arr=nil
6.1.4 Iterator traversal
a={12,56,24,76,237}
for y in pairs(a)
do
print(a[y])
end
-- 带下标
-- 迭代器遍历
b={12,56,24,76,237}
for x,y in pairs(b)
do
print(x,":",y)
end
6.2 Linked list
6.2.1 Declaration
dictionary-like
local a={key=123,value=234}
print(a.value)
6.2.2 Traversing linked lists
-- 迭代器遍历
local a={key=123,value=234}
for x,y in pairs(a)
do
print(x,":",y)
end
6.3 Common methods
6.3.1 concat
The operation of connecting a table at the specified start and end positions with the specified separator (the subscript starts from 1)
arr1={"erw","dfsf","qwrqw","rqwr"}
arr2=table.concat(arr1,"~",1,3)
print(arr2)
6.3.2 insert
arr1={"erw","dfsf","qwrqw","rqwr"}
table.insert(arr1,3,"hello")
for x,y in pairs(arr1)
do
print(x,":",y)
end
6.3.3 remove
arr1={"erw","dfsf","qwrqw","rqwr"}
table.remove(arr1,3)
for x,y in pairs(arr1)
do
print(x,":",y)
end
6.3.4 sort
arr1={2,37,23,83,54}
table.sort(arr1)
for x,y in pairs(arr1)
do
print(x,":",y)
end
-- 指定排序规则
-- 如从大到小排列
arr1={2,37,23,83,54}
table.sort(arr1,function(a,b) return a>b end)
for x,y in pairs(arr1)
do
print(x,":",y)
end
7. Modules and packages
7.1 Module call
-- 文件名为 module.lua
-- 定义一个名为 module 的模块
module = {
}
-- 定义一个常量
module.constant = "这是一个常量"
-- 定义一个函数
function module.func1()
io.write("这是一个公有函数!\n")
end
local function func2()
print("这是一个私有函数!")
end
function module.func3()
func2()
end
return module
call module
require("module")
print(module.constant)
module.func3()
7.2 Module loading
require 用于搜索 Lua 文件的路径是存放在全局变量 package.path 中,当 Lua 启动后,会以环境变量 LUA_PATH 的值来初始这个环境变量。如果没有找到该环境变量,则使用一个编译时定义的默认路径来初始化。
可以自定义:文件路径以 ";" 号分隔,最后的 2 个 ";;" 表示新加的路径后面加上原来的默认路径。
export LUA_PATH="~/lua/?.lua;;"
Use the C package
Different from writing packages in Lua, C packages must be loaded and linked before being used. The easiest way to implement it in most systems is through the dynamic link library mechanism.
Lua provides all dynamic linking functionality in a function called loadlib. This function takes two parameters: the absolute path to the library and the initialization function.
local path = "/usr/local/lua/lib/libluasocket.so"
-- 或者 path = "C:\\windows\\luasocket.dll",这是 Window 平台下
local f = assert(loadlib(path, "luaopen_socket"))
f() -- 真正打开库
8. Documents
8.1 Common methods
mode
r opens the file read-only, the file must exist.
w opens a write-only file. If the file exists, the file length is cleared to 0, that is, the content of the file will disappear. Create the file if it does not exist.
a Opens the write-only file in an appended manner. If the file does not exist, it will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be preserved. (EOF character reserved)
r+ opens the file for reading and writing, the file must exist.
w+ opens a readable and writable file. If the file exists, the file length will be cleared to zero, that is, the content of the file will disappear. Create the file if it does not exist.
a+ is similar to a, but this file is readable and writable
b binary mode, if the file is a binary file, you can add b
+ indicates that the file can be read and written
func
io.write()
io.flush()
io.close()
io.open(filename,mode)
8.1.1 Create Folder
os.execute('mkdir luadirtest')
f = assert(io.open('luanewfile.txt','w'))
f:close()
8.2 Output files
output a line
local file=io.open('luanewfile.txt','r')
io.input(file)
print(io.read())
io.close()
Output line by line (no blank line at the end)
for i in io.lines('luanewfile.txt') do
print(i)
end
--使用文件句柄
local file=io.open('luanewfile.txt','r')
for i in file:lines() do
print(i)
end
file:close()
output the entire file (with a blank line at the end)
local file=io.open('luanewfile.txt','r')
io.input(file)
print(io.read('*a'))
io.close()
--使用文件句柄
local file=io.open('luanewfile.txt','r')
print(file:read('*a'))
file:close()
--'*a' 读取整个文件
--'*l' 读取下一行(不包括换行符)=io.read()
--'*L' 读取下一行(包括换行符)
--'*n' 读取一个数字(非数字开头返回nil,数字开头直到读到非数字)
--num 读取num个字符
8.3 Writing to a file
local file=io.open('luanewfile.txt','w')
io.output(file)
io.write('hello world')
io.close()
--文件句柄
local file=io.open('luanewfile.txt','w')
file:write("hey go")
file:close()
8.4 File Pointers
"set": base point is 0 (beginning of file)
"cur": The base point is the current position, the default
"end": the base point is the end of the file
-- 从文件开头算起,跳过3个字符,然后输出2个字符
local file=io.open('luanewfile.txt','r')
file:seek('set',3)
print(file:read(2))
file:close()
-- 从文件结尾算起,往前推5个字符,然后输出2个字符
Reference link:
https://www.runoob.com/lua/lua-tutorial.html
https://www.sohu.com/a/468031584_120372431
https://www.sohu.com/a/464455971_120372431
https:// www.sohu.com/a/466566945_120372431
If there is anything wrong, please point it out, thank you~