github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/base/collectgarbage.go (about) 1 package base 2 3 import ( 4 "errors" 5 "runtime" 6 "runtime/debug" 7 8 rt "github.com/arnodel/golua/runtime" 9 ) 10 11 var gcPercent int 12 var gcRunning bool 13 14 func collectgarbage(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) { 15 opt := "collect" 16 if c.NArgs() > 0 { 17 optv, err := c.StringArg(0) 18 if err != nil { 19 return nil, err 20 } 21 opt = string(optv) 22 } 23 next := c.Next() 24 switch opt { 25 case "collect": 26 t.CollectGarbage() 27 case "step": 28 // The Go runtime doesn't offer the ability to go gc steps. 29 t.CollectGarbage() 30 t.Push1(next, rt.BoolValue(true)) 31 case "stop": 32 debug.SetGCPercent(-1) 33 gcRunning = false 34 case "restart": 35 debug.SetGCPercent(gcPercent) 36 gcRunning = gcPercent != -1 37 case "isrunning": 38 t.Push1(next, rt.BoolValue(gcRunning)) 39 case "setpause": 40 // TODO: perhaps change gcPercent to reflect this? 41 case "setstepmul": 42 // TODO: perhaps change gcPercent to reflect this? 43 case "count": 44 stats := runtime.MemStats{} 45 runtime.ReadMemStats(&stats) 46 t.Push1(next, rt.FloatValue(float64(stats.Alloc)/1024.0)) 47 default: 48 return nil, errors.New("invalid option") 49 } 50 return next, nil 51 } 52 53 func init() { 54 gcPercent = debug.SetGCPercent(-1) 55 gcRunning = gcPercent != -1 56 debug.SetGCPercent(gcPercent) 57 }