Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Patch for the Lua Garbage Collector API #997

@gamagan

Description

@gamagan

Please add the following patch to sol.hpp to enable support for the full Lua GC api. I certify that I wrote this code myself, and I release it into the public domain. Some of the comments I got from the Lua manual.

If you search for the existing function 'collect_garbage', i would place it around there.


		// Synonym for gc_collect().
		void collect_garbage() {
			gc_collect();
		}

		// Performs a full garbage-collection cycle.
		void gc_collect() {
			lua_gc(lua_state(), LUA_GCCOLLECT, 0);
		}

		// Returns true if the collector is enabled(not stopped), or false if it's disabled(stopped).
		bool gc_is_enabled() {
			return 1 == lua_gc(lua_state(), LUA_GCISRUNNING, 0);
		}

		// Restarts automatic execution of the garbage collector. 
		void gc_restart() {
			lua_gc(lua_state(), LUA_GCRESTART, 0);
		}

		// Stop performing automatic garbage collection.
		void gc_stop() {
			lua_gc(lua_state(), LUA_GCSTOP, 0);
		}

		// Performs a garbage-collection step. The "step size" controls the amount of work done in the step.
		// With a zero value, the collector will perform one basic (indivisible) step. 
		// For non-zero values, the collector will perform as if that amount of memory (in kbytes) had been allocated by Lua. 
		// Returns true if the step finished a collection cycle, or false otherwise.
		bool gc_step(int step_size = 0) {
			return 1 == lua_gc(lua_state(), LUA_GCSTEP, step_size);
		}

		// Get the total amount of memory used by the garbage collector, in bytes.
		int gc_get_total_memory_used() {
			int size = lua_gc(lua_state(), LUA_GCCOUNT, 0); // Returned as kilobytes.
			size    *= 1024; // Make into bytes -- https://www.lua.org/manual/5.4/manual.html#pdf-collectgarbage
			size    += lua_gc(L, LUA_GCCOUNTB, 0);
			return size;
		}

#if SOL_LUA_VERSION >= 504

		// Set the garbage collector mode to incremental. This is the default mode.
		// For param info, see: https://www.lua.org/manual/5.4/manual.html#2.5.1
		void gc_mode_incremental(int pause, int step_mult, int step_size) {
			lua_gc(lua_state(), LUA_GCINC, pause, step_mult, step_size);
		}

		// Set the garbage collector mode to generational.
		// For param info, see: https://www.lua.org/manual/5.4/manual.html#2.5.1
		void gc_mode_generational(int minor_mult, int mayor_mult) {
			lua_gc(lua_state(), LUA_GCGEN, minor_mult, mayor_mult);
		}

#endif

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions