lua学习日志day03-----闭包思想

【信息科学与工程学】计算机科学与自动化 第二百三十三篇 凤凰架构01 编号类型领域系统软件/硬件或系统集成方案及系统架构模块子模块函数名称/算法名称算法的数学分析及计算机体系架构及数据结构与算法详细设计及参数列表及数值范围设计关联知识1共识算法分布式基石状态机复制架构:Proposer/Acceptor/Learner 多节点角色模型,基于操作转移(Operation Transfer)分布式共识PaxosPaxos 协议(Prepare/Promise/Accept/Accepted 两阶段)数学基础:多数派(Quorum)投票,基于鸽巢原理保证 W+R>N 时读写集合必有 阅读详情

在lua中函数作为第一类值,可以像变量一样,被用作给其他变量赋值,给其他函数当作参数。

词法界定:内部嵌套的函数可以调用外部函数的局部变量。

匿名函数:

先讨论一下函数的定义,函数是可以用以下形式定义:

fun = function (x) print(“abc”)end

这样的形式就像是一个参数,当函数作为另一个函数的实参的时候,是可以不需要函数名的,也就是匿名函数。

funOne = function (fun1) fun1()end

funOne(function (x)print(“abc”)end)

同理,当一个函数作为另一个函数的返回值的时候,也是可以作为匿名函数的。当让这种情况基本都和闭包思想一起使用的。


下面来浅谈以下闭包的思想:

对闭包解释的原文如下:

从技术上讲,闭包指值而不是函数,函数仅仅是闭包的一个原型声明;尽管如此,在不会导致混淆的情况下我们继续使用属于函数指代闭包

从字面上理解闭包,就是,一个函数内有一个嵌套的函数,这个函数用外部函数的值做了一些事,最后在外部函数 return的位置,返回了这个内嵌函数。

PS:

function fun1 (x)

       return function ()

                         x = x + 1

                         print(x)

                 end

end


fun = fun1(1)

用原文的话去解释就是,当fun1执行到return的时候,fun1这个函数已经结束,但是在 return后续的嵌套函数中,调用了超出范围的x变量,这个变量叫做 外部的局部变量。

上面这个例子,进入交互模式之后,用dofile(fun())多次调用就会发现它输出的值在累加。

那么闭包到底是什么呢?

按照目前我的理解,

它类似于c++中的一个类的实例,但是不一样。

闭包就是内嵌函数在使用外部的局部变量之后产生的一个值,这个值能保存自己当前的状态。


还有一点比较注意,在原文中解释闭包的时候,强调的是内嵌函数使用了超出范围的变量。那么正常的情况下,局部变量只有超出了它所在chunk,代码块,函数才算是超出范围,如果仅仅针对函数,那么内嵌函数的位置,是不是永远只能在外部函数return语句的后面。也就是说,要产生一个闭包,必须外部函数返回的是一个函数的值。

大型国有银行应用系统全链路性能劣化智能根因定位与自愈Agent平台详细设计方案.docx 立即下载

相关推荐

【深度学习开发环境配置】基于PyTorch的计算机视觉项目依赖管理:requirements.txt文件解析与版本控制方案

内容概要:该文件为一个Python项目的依赖包配置文件(requirements.txt),列出了项目运行所需的软件包及其最低版本要求。主要包括深度学习框架PyTorch及其视觉扩展 torchvision、科学计算库 numpy 和 scipy、数据处理工具 pandas、机器学习库 scikit-learn、图像处理库 opencv-python 和 Pillow,以及数据可视化工具 matplotlib 和 seaborn 等。该配置确保项目在不同环境中具备一致的运行条件。; 适合人群:从事深度学习、计算机视觉或数据科学相关工作的开发者与研究人员,熟悉Python环境管理的技术人员; 使用场景及目标:①用于搭建项目开发环境,确保依赖一致性;②支持模型训练、图像处理、数据分析等任务的环境准备;③便于项目共享与部署,降低环境配置成本; 阅读建议:在实际使用时,建议通过 pip install -r requirements.txt 安装依赖,并根据具体硬件环境适当调整版本兼容性,尤其注意 PyTorch 与 CUDA 版本的匹配。

深入理解Lua的闭包一:概念、应用和实现原理

本文首先通过的例子讲解了Lua中闭包的概念,然后总结了闭包的应用场合,最后探讨了Lua中闭包的实现原理。 闭包的概念 在Lua中,闭包(closure)是由一个函数和该函数会访问到的非局部变量(或者是upvalue)组成的,其中非局部变量(non-local variable)是指不是在局部作用范围内定义的一个变量,但同时又不是一个全局变量,主要应用在嵌套函数和匿名函数里,因此若一个闭包没有会

MaximusZhou的专栏 3万+

用AI Agent搭建视频创作流水线:从Hermes到WorkBuddy的实践

AI智能体正从单轮对话走向多角色协同,其核心原理在于将复杂任务拆解为可编排的工作流:每个智能体承担独立职责,通过标准化输入输出传递上下文,最终形成自动化生产流水线。这种协同模式在内容创作领域价值显著,尤其是视频生产——从选题分析、脚本撰写、分镜设计到标题包装,均可被模块化为不同智能体的任务。实际工程落地时,工具选型至关重要:开源Agent框架灵活但配置成本高、维护负担重,而可视化工作台通过流程编排与Skill机制降低了使用门槛。以视频内容生产为例,接入DeepSeek等大模型API、按角色配置参数、加入人工

weixin_34014555的博客 270

编程日记 - 零基础学习《Lua - 脚本语言》教程

全局变量 全局变量不需要声明 没有初始化的全局变量也不会出差,只是得到结果nil print(a) --> nil a = 1 print(a) --&

Carlos 1万+

实测有效!YOLOv8融合EMA注意力机制后,在无人机航拍目标检测中的性能提升对比

本文详细介绍了YOLOv8融合EMA注意力机制在无人机航拍目标检测中的性能提升效果。通过多尺度特征融合和通道-空间双重注意力机制,EMA模块显著提升了小目标检测的准确率,mAP@0.5平均提升4.2%,同时保持推理速度基本不变。文章还提供了模型定制、训练技巧和实际部署优化的全流程指南。

weixin_33704234的博客 394

Power Automate Desktop实战:一键自动登录Chrome网站

本文详细介绍了如何使用Power Automate Desktop实现Chrome网站的一键自动登录,提升工作效率。从环境准备、基础配置到高级技巧与异常处理,全面解析自动化登录流程的构建与优化,特别适合需要频繁登录多个系统的用户。

weixin_29231725的博客 472

lua学习笔记day04-----无状态和多状态的迭代器

在解释无状态和多状态的迭代器之前,我们需要先了解一下泛型for是如何和迭代函数一起工作的。 泛型for的格式: for 1 in 2 do      code end in的后面会放置一个迭代函数的生成函数

displayMessage的博客 1617

YOLOv11 改进 - 注意力机制 | 空间增强注意力SEAM(Spatially Enhanced Attention Module)提升遮挡场景检测鲁棒性

本文介绍了分离与增强注意力模块(SEAM)在YOLOv11中的结合应用。SEAM模块旨在增强面部特征学习能力,特别是处理面部遮挡问题。它采用多头注意力机制强调面部区域、抑制背景区域,第一部分使用深度可分离卷积减少参数并学习通道重要性,通过1x1卷积增强通道联系,利用两层全连接网络融合通道信息,经指数归一化后作为注意力权重与原始特征相乘。我们将SEAM集成到YOLOv11的检测头中,并进行相关注册和配置。实验表明,该方法有助于提升模型检测性能。

魔改工程师的博客 1676

lua学习笔记day13-----对象的私有性

对象的私有化

displayMessage的博客 775

华为od统一考试B卷【宜居星球改造计划】Java&Go 实现

XXX年,人类通过对火星的大气进行宜居改造分析,使得火星已在理论上具备人类宜居的条件,由于技术原因,无法一次性将火星大气全部改造,只能通过局部处理形式,假设将火星待改造的区域为row * column的网格每个网格有3个值,宜居区、可改造区、死亡区,使用YES、NO、NA代替,YES表示该网格已经完成大气改造,NO表示该网格未进行改造,后期可进行改造,NA表示死亡区,不作为判断是否改造完成的宜居,无法穿过 初始化下,该区域可能存在多个宜居区,并且每个宜居区能同时在每个太阳日单位向上下左右四个方向的相邻格子进

MISAYAONE的博客 1万+

Python爬虫教程:爬取法院司法拍卖数据全流程实战(附反爬+数据分析方案)

Python爬虫爬取法院司法拍卖数据的核心是模拟真人行为规避反爬+精准解析页面数据+合理处理数据。新手不用一开始就追求高级的反爬技巧和复杂的数据分析,先把基础的分页爬取和数据保存功能跑通,再逐步优化。我做的这个工具现在每周帮朋友爬取全国10个城市的法拍房数据,自动生成分析报告,他说这让他的投资决策效率提升了一倍。如果你们在开发过程中遇到问题,比如反爬失败、数据解析错误,都可以在评论区留言,我会尽力解答。后续我还会出一期爬取京东司法拍卖数据的教程,帮助大家获取更多的法拍数据来源。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 2198

lua学习笔记day12-----环境

_G,_ENV,setfenv,全局环境/变量,非全局环境/变量

displayMessage的博客 708

从零开始讲DDR(5)——读懂Datasheet

对于开发人员来说,需要根据实际场景和使用的需要,使用不同厂家,不同型号的DDR,虽然原理上大同小异,但是还是有一些细节上的需要注意的地方,接触一个新的DDR芯片,首先就是需要找到对应的datasheet,而能都读懂datasheet,也是一个硬件工程师的必备技能。

apple_53311083的博客 5246

lua学习笔记day11-----默认值的表,监控表,只读表

metatable中__index 和 __newindex的几种用法, 带默认值的表,监控表,只读表

displayMessage的博客 496

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lua学习笔记day09-----数据文件与持久化

lua中对表的保存,循环表,共享表

displayMessage的博客 427

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

lua学习笔记day07-----协同函数和非抢占式多线程

协同,非抢占式多线程

displayMessage的博客 383

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

lua学习笔记day13-----类,继承,多继承

类,继承,多继承

displayMessage的博客 365

lua学习笔记day08-----lua中的数据结构

lua的tables和数据结构

displayMessage的博客 319

lua学习笔记day11-----metatable 和 metamathods 的关系运算

metatable 和 metamathods 的关系运算

displayMessage的博客 310

lua学习笔记day04-----泛型for和迭代器

在lua的手册中,对迭代器的解释如下: 迭代器是一种指针类型的结构, 首先要明白迭代器,泛型for是两个东西。 迭代器可以不由泛型for和闭包组成。 高效的迭代器可以由泛型for和闭包来实现。

displayMessage的博客 275

lua学习笔记day12-----包,文件

package中使用非全局环境

displayMessage的博客 269

lua学习笔记day10-----metatables and metamethods的算数运算

Metatable 和 metamethods 的算数运算

displayMessage的博客 259

lua学习笔记11-----表相关的metatable and metamathods

metatable中的__index 和 __newindex介绍

displayMessage的博客 254

lua学习笔记day06-----协同函数和迭代器

比起前面提到的协同程序和过滤器,我觉的迭代器和协同程序的结合会看起来简单一些。 我们知道一个迭代器,是要遍历每一个元素。 而lua的迭代器,其实只是描述了迭代一次的过程,循环是由外置的循环语句完成的。 我们继续在之前提到的泛型for和迭代器的组合里加入协同函数。 function progrem(a,n) if n == 0 then cor

displayMessage的博客 246
上一篇: lua学习笔记day02-----函数
下一篇: c++学习比较day02-----标准c语言
displayMessage
博客等级 码龄11年 34粉丝 114原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址