Comparison

util/gc.lua @ 10933:f59bc81245b3

util.gc: New module for configuring the Lua garbage collector
author Matthew Wild <mwild1@gmail.com>
date Mon, 15 Jun 2020 14:16:10 +0100
child 10935:2d57c49bfa12
comparison
equal deleted inserted replaced
10932:ea4a7619058f 10933:f59bc81245b3
1 local array = require "util.array";
2 local set = require "util.set";
3
4 local known_options = {
5 incremental = set.new { "mode", "threshold", "speed", "step_size" };
6 generational = set.new { "mode", "minor_threshold", "major_threshold" };
7 };
8
9 if _VERSION ~= "5.4" then
10 known_options.generational = nil;
11 known_options.incremental:remove("step_size");
12 end
13
14 local function configure(user, defaults)
15 local mode = user.mode or defaults.mode or "incremental";
16 if not known_options[mode] then
17 return nil, "GC mode not supported on ".._VERSION..": "..mode;
18 end
19
20 for k, v in pairs(user) do
21 if not known_options[mode]:contains(k) then
22 return nil, "Unknown GC parameter: "..k;
23 elseif k ~= "mode" and type(v) ~= "number" then
24 return nil, "parameter '"..k.."' should be a number";
25 end
26 end
27
28 if mode == "incremental" then
29 if _VERSION == "Lua 5.4" then
30 collectgarbage(mode,
31 user.threshold or defaults.threshold,
32 user.speed or defaults.speed,
33 user.step_size or defaults.step_size
34 );
35 else
36 collectgarbage("setpause", user.threshold or defaults.threshold);
37 collectgarbage("setstepmul", user.speed or defaults.speed);
38 end
39 elseif mode == "generational" then
40 collectgarbage(mode,
41 user.minor_threshold or defaults.minor_threshold,
42 user.major_threshold or defaults.major_threshold
43 );
44 end
45 return true;
46 end
47
48 return {
49 configure = configure;
50 };