当前位置:网站首页>Lua -- iterator, module, meta table
Lua -- iterator, module, meta table
2022-06-22 22:33:00 【aruba】
next lua Use , iterator 、 Modules and meta tables , Meta table is the key content that needs attention
One 、 iterator
pairs It's an iterator , Its return value is key and value, Let's customize an iterator
Define iterator Syntax : function Iterator name ( End value parameter , Initial value parameter ) end
Use iterator Syntax : for The first return value , Second return value in Iterator name , Termination value , Initial value do end
-- The first parameter : Termination value The second parameter : Initial value
function double(max,init)
if(init < max) then
init = init + 1
return init,init*2
end
end
-- in Back , Follow the iterator name , Termination value , Initial value
for i,d in double,10,0 do
print(i,d)
endRunning results :
Two 、 modular
lua5.1 Start supporting modules , Functions can be encapsulated in modules , Reference modules in other scripts
1. New module
-- Define modules
module = {}
-- Module constants
module.name = ' My module '
module.time = '2022'
-- Methods of public disclosure Use module. Method name definition
function module.func1()
print("func1")
end
-- Internal methods , Cannot add moudle.
local function func2()
print("func2")
end
function module.func3()
func2()
end
-- Return module
return module2. Other scripts introduce modules
-- Introduce modules
require("module")
print(module.name..module.time)
print(module.func1())
print(module.func3())Running results :
3、 ... and 、 Metatable
Meta table allows you to change table act , Yes table Extend in disguise , It can even achieve the function of simulating classes
1. Meta table definition and use
Meta table and table equally , Use {} Definition , The use of meta tables needs to be combined with ordinary tables , call setmetatable Method
a = {1,2,3} -- Common watch
b = {} -- Metatable
c = setmetatable(a,b)
print("table:",a)
print("metatable:",b)
print("ret:",c)
print("getmetatable:",getmetatable(c))Running results :
You can find setmetatable The return value of is a normal table ,getmetattable The return value of is meta table
2. index Metamethod
index The meta method is defined as {__index = value }, There are two uses
2.1 Combine two common tables
-- Two ordinary watches
e = {'a','b'}
f = {c = 'c'}
-- Meta table will index The meta method is assigned to f
g = {__index = f}
-- by e Table set meta table
setmetatable(e,g)
print(e['c'])Running results :
2.2 The extension does not correspond to key Method of value taking
-- Common watch
e = {'a','b'}
-- Meta table will index The meta method is assigned to a function
g = {
__index = function(tab,key)
if(key[tab] == nil) then
return 'null'
end
end
}
-- by e Table set meta table
setmetatable(e,g)
print(e['c'])
print(e[1])Running results :
3. newindex Metamethod
newindex The meta method is defined as {__newindex = value }, There are also two uses
3.1 Store the new element in another normal table
-- Two ordinary watches
e = {'a','b'}
f = {}
-- Meta table will newindex The meta method is assigned to f
g = {__newindex = f}
-- by e Table set meta table
setmetatable(e,g)
-- Set new element
e[5] = 'f'
print(e[5])
print(f[5])Running results :
3.2 Extension insert new element method
-- Common watch
e = {'a','b'}
-- Meta table will newindex The meta method is assigned an anonymous function
g = {
__newindex = function(tab,key,val)
print(" new key:"..key," new value:"..val)
rawset(tab,key,val)
end
}
-- by e Table set meta table
setmetatable(e,g)
e['a'] = 'hello'
print(e['a'])Running results :
4. Operator overloading
The operator overloading of the meta table is defined as follows :
The way | Corresponding operator |
|---|---|
__add | + |
__sub | - |
__mul | * |
__div | / |
__mod | % |
__concat | .. |
__eq | == |
__lt | < |
__le | <= |
__gt | > |
__ge | >= |
test , Merge two table:
-- Operator overloading
a = {'a','b'}
b = {'c','d'}
c = {
__add = function(tab1,tab2)
-- Get the first one table The length of
local t1_len = #tab1
-- Traversal of the second table
for k,v in pairs(tab2) do
t1_len = t1_len + 1
-- Put the second tab The value of is assigned to the first tab
tab1[t1_len] = v
end
return tab1
end
}
setmetatable(a,c)
a = a + b
for k,v in pairs(a) do
print(v)
endRunning results :
5. call Metamethod
When a table is called as a function , Will trigger
-- call Metamethod
a = {1,2}
c = {
__call = function(tab,...)
for k,v in pairs({...}) do
print(k,v)
end
end
}
setmetatable(a,c)
a(1,2,3,5,6,7)Running results :
6. tostring Metamethod
Rewrite the method of printing , and Java It's similar to
a = {'a','c','e'}
c = {
__tostring = function(tab)
local ret = ''
for k,v in pairs(tab) do
ret = ret..v..','
end
return ret
end
}
setmetatable(a,c)
print(a)Running results :
边栏推荐
- Implementation of breadth traversal adjacency matrix of 6-6 graph
- LinkedList 源码解析
- 【李沐】 如何读论文【论文精读】
- 【几何法视觉】4.2 分段线性变换
- Makefile:1860: recipe for target ‘cmake_ check_ build_ system‘ failed make: *** [cmake_check_build_syst
- [recommended by Zhihu knowledge master] castle in UAV - focusing on the application of UAV in different technical fields
- [ROS introduction] cmakelist Txt and packages XML interpretation
- 立体渲染
- Core and semiconductor "RF eda/ filter design platform" shines ims2022
- Wechat applet batch submission for review
猜你喜欢

Database summary: common problems and Optimization in MySQL development

Implementation of depth traversal adjacency table in Figure 6-7

Rapideye, spot satellite remote sensing image data

6-7 图的深度遍历-邻接表实现

自助圖書館系統-Tkinter界面和openpyxl錶格綜合設計案例

5 minutes to quickly launch web applications and APIs (vercel)

Liunx installing MySQL

Implementation of breadth traversal adjacency matrix of 6-6 graph
Task cache compilation caused by gradle build cache

【路径规划】第一周: 大杂烩
随机推荐
R language data Table data import practice: data Rename the name of the table data column (rename)
Core and semiconductor "RF eda/ filter design platform" shines ims2022
Reasons for the failure of digital transformation and the way to success
Grafana report display of sentinel based high availability current limiting system
Linux安装Mysql(包成功!!)
The xinjietu x70s has been listed for 87900 times and has leapfrogged the class in space safety. It is worthy of being a 7-seat SUV of the National University of China
[ROS introduction] cmakelist Txt and packages XML interpretation
7-9 超级玛丽
Research hotspot - Official publicity! The release time of JCR zoning and impact factors will be determined in 2022!
Eureka service registration and discovery
redis 报错解决与常用配置
Task management of embedded development foundation (thread management)
新捷途X70S上市8.79万起,空间安全越级,不愧是网红国民大7座SUV
PMP Exam admission ticket problems and precautions in June, which must be read by candidates
[Li mu] how to read papers [intensive reading of papers]
二级造价工程师考前必备15个知识点来了!祝你旗开得胜!
In the third week of June, the main growth ranking list (BiliBili platform) of station B single feigua data up was released!
Seriously, the hang up of the kotlin collaboration process is not so mysterious (principle)
The necessary materials for the soft test have been released. All the soft test materials for the whole subject have been prepared for you!
【知乎知识主推荐】 无人机中的城堡- 专注于无人机在不同技术领域的应用