Do I need numbers, bools or nils trash in Lua?

This article assumes that all types next to numbers, bools and nil are garbage collected.

The gc field is used for other values ​​(rows, tables, functions, heavy user data and threads) that are garbage collection objects.

Would this mean in certain circumstances that using these non-gc types could lead to memory leaks?

+4
source share
2 answers

In Lua, you actually have 2 types of types: Ones, which are always passed by value, and those that are passed by reference (according to chapter 2.1 in the Lua Guide ).

The ones you quote are types of "passed value", so they are directly stored in the variable. If you delete the variable, the value will be immediately disabled.

Thus, it will not trigger a memory leak, unless, of course, you will not generate new variables containing new values. But in this case, this is your own mistake;).

+2
source

In the article you contacted, they write C code that shows how the values ​​are represented:

/*You can also find this in lobject.h in the Lua source*/ /*I paraphrased a bit to remove some macro magic*/ /*unions in C store one of the values at a time*/ union Value { GCObject *gc; /* collectable objects */ void *p; /* light userdata */ int b; /* booleans */ lua_CFunction f; /* light C functions */ numfield /* numbers */ }; typedef union Value Value; /*the _tt tagtells what kind of value is actually stored in the union*/ struct lua_TObject { int _tt; Value value_; }; 

As you can see here, Booleans and numbers are stored directly in the TObject structure. Since they are not “distributed in a heap”, this means that they can never “leak”, and therefore garbage collection does not make sense.

It is interesting to note, however, that the garbage collector does not collect links created for things on the C side of things (user data and CC functions). They must be manually managed by C, but this is kind of expected since in this case you are writing C instead of Lua.

+1
source

All Articles