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")
- 理解上可能會有點問題,所以先把原本的注釋先拷貝過來,下面是我自己的理解
- collect : 立馬執行一遍完整的垃圾回收
- count: 得到當前應用的當前內存消耗,返回值是用Kb計算的
- restart: 就是Garbage collector 停止掉后重新啟動
- setpause: 使用的正確格式
collectgarbage("setpause", 200)
意思就是當收集器在總使用內存數量達到上次垃圾收集時的兩倍時再開啟新的收集周期,而如果200是100時表示不停的進行垃圾回收- setstepmul: 使用的正確格式
collectgarbage("setstepmul", 500)
,第二個值有一個默認值200, 表示垃圾收集器的運行速度是內存分配的2倍。
3.最后的解決方案,不考慮性能,初步解決
collectgarbage('setpause')
collectgarbage('collect')