当前位置:网站首页>Closure problem C Lua
Closure problem C Lua
2022-06-26 06:32:00 【ThomasQxx】
Closure problem summary ( There was a big guy who asked a few questions from time to time , Now let's sum up the experience )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ToggleTest : MonoBehaviour
{
public Toggle[] toggles;
private void Start() {
for (int i = 0; i < toggles.Length; i++)
{
toggles[i].onValueChanged.AddListener((isOn)=>OnToggleChanged(isOn,i));
}
}
private void OnToggleChanged(bool isOn,int index){
Debug.Log($"index==>{
index}..State===>{
isOn}");
}
}
Here you can guess and choose Toggle What will the print result be ?Toggle There are three radio buttons .
You can see Index Always be 3...
Why would the result be 3 Well ? The concept of closure will be mentioned here : The inner function can refer to the variables of the function contained in its outer layer , Even if the execution of the outer function has terminated . However, the value provided by this variable is not the value at the time of variable creation , But the final value in the range of the parent function . Normally speaking For When the loop is finished i The memory of variables will change with For The cycle ends and life ends . But because anonymous functions refer to i, Lead to i Can't go with For The end of the cycle . So at this point i=3. When we execute a click index=3. Here is the problem , So how to solve it ?
Solution

That's it . Want to figure out the solution , We still have to start with memory . The last one did not int t = i In the code of .i There are several memory addresses ? You can see it i Only one memory address . In the current figure t There are several memory addresses ? There are obviously three , Every time For Loop in will declare a t Memory address of . also t The value of the For The end of the loop is different . Namely 0,1,2. So the problem can be fully understood here .

Lua Closure in
function newCounter()
local i = 0
return function()
i = i + 1
return i
end
end
c1 = newCounter()
print(c1())
print(c1())
The result should be 1,2.i It should have been NewCounter At the end of the call, the memory is released . But because of the internal function reference , So memory continues to exist , First execution completed c1()i = 0+1 = 1; Second execution c1() End i It should be for i = 1+1 =2;
function newCounter()
local i = 0
return function()
i = i + 1
return i
end
end
c1 = newCounter()
print(c1())
c1 = nil
c2 = newCounter()
print(c2())
The result should be 1,1. Because after the first execution c1()i = i + 1 = 0 + 1 = 1; But next c1=nil It frees up memory .c2 = newCounter() perform c2() At this time i by 0. therefore c2() The result is i = i + 1 = 0 + 1 = 1; So the end result is 1,1.
边栏推荐
- 事务与消息语义
- Gof23 - prototype mode
- Unsatisfied dependency expressed through field ‘baseMapper‘; nested exceptio
- Five solutions across domains
- Reasons why MySQL indexes are not effective
- Simple use of enum type in TS
- Research Report on pallet handling equipment industry - market status analysis and development prospect forecast
- 视图简析
- Transaction and message semantics
- Data visualization practice: Experimental Report
猜你喜欢

成水最多的容器

实时数仓方案如何选型和构建

Mysql delete in 不走索引的

GoF23—抽象工厂模式

How to design a good technical scheme

Gof23 - abstract factory pattern

C# Nuget离线缓存包安装

TCP連接與斷開,狀態遷移圖詳解
The sysdig 2022 cloud native security and usage report found that more than 75% of the running containers have serious vulnerabilities

Jasminum plug-in of Zotero document management tool
随机推荐
直播预告丨消防安全讲师培训“云课堂”即将开讲!
Gof23 - prototype mode
寶塔服務器搭建及數據庫遠程連接
Reasons why MySQL indexes are not effective
Custom reference formats used by Zotero
typescript的class结合接口(interface)的简单使用
GoF23—抽象工厂模式
How can an enterprise successfully complete cloud migration?
Customer Stories | Netease spring breeze: the "spring breeze" of the fun industry, reaching out to all areas through in-depth interaction
University Information Management System
Laravel 实现 groupBy 查询分组数量
vs code 使用 prettier 格式化 js 的时候, 函数定义的名称和括号之间有一个空格, 而 eslit 又不允许这个空格.
个人博客系统需求分析
技术能力的思考和总结
Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource could
DS18B20详解
View analysis
Efk upgrade to Clickhouse log storage practice
Work accumulation - problems encountered in using ThreadLocal in web requests
Pytorch uses multi GPU parallel training and its principle and precautions