Lua 垃圾收集机制

1. 问题:一款用Lua做的游戏,玩了一段时间后会变卡

因为知道lua是有自动管理内存的机制,所以之前一直没有关注过lua内存的问题。所以今天好好的查看了lua垃圾收集机制。看了一下Lua的Garbage Collection

2. Garbage Collector Functions

-- Runs one complete cycle of garbage collection.
collectgarbage("collect") 

-- Returns the amount of memory currently used by the program in Kilobytes.
collectgarbage("count") 

-- If the garbage collector has been stopped, it restarts it.
collectgarbage("restart")

-- Sets the value given as second parameter divided by 100 to the garbage collector pause variable. 
collectgarbage("setpause") 

--Sets the value given as second parameter divided by 100 to the garbage step multiplier variable.
collectgarbage("setstepmul") 

--Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle.
collectgarbage("step")

--Stops the garbage collector if its running.
collectgarbage("stop")
  • 理解上可能会有点问题,所以先把原本的注释先拷贝过来,下面是我自己的理解
  1. collect : 立马执行一遍完整的垃圾回收
  2. count: 得到当前应用的当前内存消耗,返回值是用Kb计算的
  3. restart: 就是Garbage collector 停止掉后重新启动
  4. setpause: 使用的正确格式collectgarbage("setpause", 200)意思就是当收集器在总使用内存数量达到上次垃圾收集时的两倍时再开启新的收集周期,而如果200是100时表示不停的进行垃圾回收
  5. setstepmul: 使用的正确格式collectgarbage("setstepmul", 500),第二个值有一个默认值200, 表示垃圾收集器的运行速度是内存分配的2倍。

3.最后的解决方案,不考虑性能,初步解决

collectgarbage('setpause')
collectgarbage('collect')