lua:如果图像创建为本地,内存还会使用吗?
local function myInit()
local topBackGround = display.newImageRect("backGround.png", 500, 500)
topBackGround.x = 0
topBackGround.y = 0
end
据我所知,在我们跳出函数后,局部变量将不会使用内存,因为这种情况下图像仍然存在,它会使用内存吗?
如果不是,如果我将其插入全局显示组怎么办?
local function myInit()
local topBackGround = display.newImageRect("backGround.png", 500, 500)
topBackGround.x = 0
topBackGround.y = 0
end
as i know local variable will not using memory after we jump out the function, as this case the image still exits, will it using memory ?
if no, what if i insert it to a global displayGroup ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lua 是垃圾收集器。所以它仍然会存在,直到 Lua 收集它。由于没有人再拥有对该对象的引用,因此可以在函数存在后随时收集它。
然而,事实上没有任何东西可以引用该对象,这意味着您无论如何都无法使用它。您可以创建一个新对象,但它将是一个新对象,与之前的对象不同。现在,由于 Corona 会缓存图像,因此如果未收集原始图像,它可能会在内部引用同一图像。但这样做是非常糟糕的。
任何时候你在 Lua 中创建一些东西,如果你想保留它,那么你需要实际保留它。保留对它的引用。
换句话说。这:
返回一个值。 独特的价值。任何声明为
local
的变量在其作用域结束后都会被丢弃(除非它们被函数捕获为闭包)。如果在任何时候,您的程序找不到某个值,因为对它的所有引用都被丢弃,那么该值将被消除。因此,如果你想使用某样东西,你需要把它放在你可以拿到的地方。否则,Lua知道你找不到它,就会删除它。
Lua is garbage collected. So it will still exist until Lua collects it. Since nobody has a reference to the object anymore, it can be collected anytime after the function exists.
However, the fact nothing has a reference to the object means that you couldn't use it anyway. You could create a new one, but it would be a new object, not the same one as before. Now, because Corona caches images, it may internally refer to the same image if the original wasn't collected. But it's terribly bad form to do this.
Anytime you create something in Lua, if you want to keep it around, then you need to actually keep it around. Keep a reference to it.
Put it another way. This:
Returns a value. A unique value. Any variables declared
local
are discarded after their scope ends (unless they are captured by functions as closures).If at any time, your program cannot find a value, because all references to it are discarded, then that value will be eliminated. Therefore, if you want to be able to use something, you need to keep it in a place where you can get at it. Otherwise, Lua knows you can't find it and will delete it.