May 12, 2021 Lua
1.1 instance code
function createCountdownTimer(second)
local ms = second * 1000 --ms为countDown的Upvalue
local function countDown()
ms = ms -1
return ms
end
return countDown
end
local timer1 = createCountdownTimer(1)
for i = 1, 3 do
print(timer1())
end
Output:
999
998
997
1.2 Description of function closure
Upvalue
The local variable used by a function that is defined outside its function body is called the upvalue of the function. I n the previous code, the local variable ms defined in the function CountyDownTimer used by the function countDownTimer is the upvalue of countDown, but ms is only a local variable, not a upvalue. Upvalue is a special attribute of Lua that differs from C/C+ and needs to be carefully experienced in conjunction with the code.
A function and all the upvalues it uses form a function closure.
Lua function closure gives a function the ability to maintain its own state, which in this sense can be compared to a C function with static local variables. B ut there is a significant difference between the two: for Lua, a function is a basic data type -- representing an (executable) object that can have its own state; B ut for a C function with a static local variable, it is not a data type of C, much less an object instance, it is just a symbol name of a static address.
2.2 Instance code
local function create(name ,id )
local data = {name = name ,id = id} --data为obj.SetName,obj.GetName,obj.SetId,obj.GetId的Upvalue
local obj = {} --把需要隐藏的成员放在一张表里,把该表作为成员函数的upvalue。
function obj.SetName(name)
data.name = name
end
function obj.GetName()
return data.name
end
function obj.SetId(id)
data.id = id
end
function obj.GetId()
return data.id
end
return obj
end
Output:
mycreate's id:1mycreate's name:Sam
mycreate's id:1mycreate's name:Lucy
2.2 A description of the object implementation
Implementation: Put the members that need to be hidden in a table and use the table as a upvalue for the member function.
Limitations: Object-based implementations do not involve inheritance and polymorphism. O n the other hand, whether script programming requires inheritance and polymorphism depends on the situation.
3.1 Instance code (1):
local t = {}
local m = {a = "and",b = "Li Lei", c = "Han Meimei"}
setmetatable(t,{__index = m}) --表{ __index=m }作为表t的元表
for k,v in pairs(t) do --穷举表t
print("有值吗?")
print(k,"=>",v)
end
print("-------------")
print(t.b, t.a, t.c)
Output:
Li LeiandHan Meimei
3.2 Instance code (2):
local function add(t1,t2)
--‘#’运算符取表长度
assert(#t1 == #t2)
local length = #t1
for i = 1,length do
t1[i] = t1[i] + t2[i]
end
return t1
end
--setmetatable返回被设置的表
t1 = setmetatable({1,2,3},{__add = add})
t2 = setmetatable({10,20,30},{__add = add})
for k,v in pairs(t1) do
print(k,"=>",v)
end
for k,v in pairs(t2) do
print(k,"=>",v)
end
print("---------两元表相加--------------")
t1 = t1 + t2
for i = 1 ,#t1 do
print(t1[i])
end
Output:
1=>1
2=>2
3=>3
1=>10
2=>20
3=>30
--------- the two-binary table--------------
11
22
33
3.3 Description of the meta-table:
Defined:
The metameter itself is just a normal table that affects the behavior of an object by setting it to an object in a specific way, such as setmetable; W hat behaviors of an object are affected by meta-tables and how they are affected is constrained by the Lua language. F or example, in the previous code, the addition of two table objects, if there is no meta-table intervention, is a mistake; H owever, Lua specifies that meta-tables can "overload" the addition operators of objects, so if you set the meta-tables that define addition operations to those two tables, they can do the addition. Metafesgees are one of Lua's most critical concepts and are rich in content, please refer to the Lua documentation for details.
Comparison of meta-tables with C-virtual tables:
If you liken a table to an object, a meta-table is a "meta" object that can change the behavior of an object. T o some extent, meta-tables can be compared to the virtual tables of C. B ut the two are still very different: meta-tables can be dynamically changed, and the C-table is static; M etasheets can affect the behavior of many aspects of tables (and other types of objects), and virtual tables are primarily a virtual way to locate objects (with a little bit of RTTI at most).
4.1 instance code
local Robot = { name = "Sam", id = 001 }
function Robot:New(extension)
local t = setmetatable(extension or { }, self)
self.__index = self
return t
end
function Robot:SetName(name)
self.name = name
end
function Robot:GetName()
return self.name
end
function Robot:SetId(id)
self.id = id end
function Robot:GetId()
return self.id
end
robot = Robot:New()
print("robot's name:", robot:GetName())
print("robot's id:", robot:GetId())
print("-----------------")
local FootballRobot = Robot:New({position = "right back"})
function FootballRobot:SetPosition(p)
self.position = p
end
function FootballRobot:GetPosition()
return self.position
end
fr = FootballRobot:New()
print("fr's position:", fr:GetPosition())
print("fr's name:", fr:GetName())
print("fr's id:", fr:GetId())
print("-----------------")
fr:SetName("Bob")
print("fr's name:", fr:GetName())
print("robot's name:", robot:GetName())
Output:
robot's name:Sam
robot's id:1
fr's position:right back
fr's name:Sam
fr's id:1
fr's name:Bob
robot's name:Sam
4.2 Description:
Prototype mode An object is both a normal object and can also be used as a prototype object for creating other objects (i.e., class object, class object); D ynamically changing the properties of a prototype object can dynamically affect all objects based on the prototype; I n addition, an object created based on a prototype can overload any method or property that belongs to the prototype object without affecting the prototype object; A t the same time, objects created based on prototypes can also be used as prototypes to create other objects.
5.1 Instance code:
hello.lua
local pack = require "mypack" --导入包[注:包的名字与定义包的文件的名字相同(除去文件名后缀,在前面的代码中,就是“mypack”)]
print(ver or "No ver defined!")
print(pack.ver)
pack.aFunInMyPack()
print(aFunInMyPack or "No aFunInMyPack defined!")
aFuncFromMyPack()
mypack.lua
module(..., package.seeall) --定义包
ver = "0.1 alpha"
function aFunInMyPack()
print("Hello!")
end
_G.aFuncFromMyPack = aFunInMyPack
Output:
No ver defined!
0.1 alpha
Hello!
No aFunInMyPack defined!
Hello!
5.2 Description of the package:
Packages are a way to organize code.
Typically, a package is defined within a Lua file with a modele function. M odule also defines a function environment for a new package so that the global variables defined in the package are in this environment, not in an environment that uses the package's functions. U nderstanding this is critical. In the previous code, for example, "module (..., package.seeall)" means to define a package with the same name as the file that defines the package (except for the file name suffix, which is "mypack" in the previous code), and to access the function environment in which the package is used (for example, the implementation of the package uses print, which is not defined in the package, but is defined in the external environment in which the package is used).
A package is typically imported with the require function, and the package to be imported must be placed on the package path. P ackage paths can be set by package.path or environment variables. In general, the current work path is always in the package path.
Please refer to the Lua manual for more detailed instructions on the package.
Reference " Luke's Quick Start for C/ C ? Programmers"