Programming in Lua 3 Reading Notes (28th)

Source: Internet
Author: User
Tags what parameter
Date: 2014.8.15part IV the C API
32 memory management Lua dynamically manages its data structure. All data structures increase as needed and are finally released. Lua has strict control over its memory usage. When we disable a Lua state, Lua will immediately release its memory usage. In addition, all objects in Lua are managed by the garbage collector, including tables, strings, and functions, threads, and modules. The Lua memory management method is suitable for most programs. However, some special programs need to be adapted, such as running in a memory-intensive environment or reducing the memory recycle interval to the minimum value. Lua allows two levels to adapt to these situations: when the level is low, set the memory management function used by Lua to control; when the level is high, you can set some parameters to control Lua's garbage collector, or even we can control it all. This section describes the memory management of Lua.


32.1 The Allocation FunctionWhen Lua allocates memory, it neither calls malloc nor realloc, but uses allocation function to allocate and recycle memory, this function must be provided when the Lua state is created. The previously mentioned lual_newstate function for creating Lua states is an auxiliary function with default memory allocation functions. Its memory allocation function uses the standard malloc-realloc-free function in the C standard library, which is sufficient for most programs. When we need to take over the memory management of Lua, we need to use another function: lua_newstate:
lua_State *lua_newstate(lua_Alloc f, void *ud);
This function accepts two parameters: the first is a memory allocation function, and the second parameter is user data. The State created through this function is always allocated and recycled by calling F. Lua_alloc is defined:
typedef void * (*lua_Alloc) (void *ud,void *ptr,size_t osize,size_t nsize);
The first parameter is the user data provided to lua_newstate. The second parameter is the address of the allocated or recycled memory block. The third parameter is the size of the original memory block; the last parameter is the size to be allocated. Lua defines a memory block with null as size 0. When the nsize is 0, the memory management function will release the memory block pointed to by the PRT and return NULL, so that the allocated size is 0; when PTR is null, the function will allocate and return memory blocks of the given size. If the given size cannot be allocated, null is returned; if PTR is null and nsize is 0, the previous two cases will occur: NULL is returned, and the memory allocation function does not work. When PTR is not null and nsize is not 0, the memory management function will reassign the memory block, similar to the realloc operation, and then return a new address. If an error occurs, null is returned. Lua assumes that the new allocation size is not smaller than the original size during memory management. The standard memory management functions used by lual_newstate are defined as follows:
void *l_alloc (void *ud,void *ptr ,size_t osize,size_t nsize){     if (nsize == 0)     {          free(ptr);          return NULL;     }     else          return realloc(ptr,nsize);}
The function assumes that free (null) does not perform any operation, and realloc (null, size) is equal to malloc (size ). The ansi c standard supports these two assumptions. You can use the lua_getallocf function to obtain a Lua state Memory Manager:
lua_Alloc lua_getallocf(lua_State *L,void **ud);
When the UD parameter is null, the function will set the UD as the user State value of this state. Of course, you can use the lua_setallocf function to change the memory manager of a State:
void lua_setallocf(lua_State *L,lua_Alloc f, void *ud);
Remember: any new manager is responsible for managing the memory managed by the original manager. Or, the new manager is a package of the original manager.


32.2 The Garbage CollectorUntil lua5.0, Lua uses the Garbage Collector (GC) in the simple mark-sweep mode. This recycler is also known as the "stop the world" recycler. This means that Lua will occasionally stop interpreting the main program for garbage collection. Each cycle goes through three steps: Mark, cleaning, and sweep. Lua marks the alive of its object from its root set, including the objects that can be accessed directly: Registry and main thread. Any objects stored in the live object can be accessed by the program and therefore marked as alive. When all the objects that can be accessed are marked as alive, the mark step is completed. Before starting the sweep step, Lua executes the cleaning step, which is related to finalizer and weak table. First, traverse all objects marked by finalization to see if there are untagged objects. Objects marked as alive will be stored in a separate linked list for use in the finalization stage. Then, Lua traverses the weak table and removes the key or value unmarked entries from it. The sweep stage traverses all the Lua objects. If an object is not marked as alive, Lua recycles it. When marked as alive, Lua will clear its mark status and prepare for the next recycling cycle. In the sweep stage, Lua also calls the objects separately stored in the cleaning stage of finalizer. In lua5.1, an incremental collector is added, which works similar to the previous recycler, but does not stop interpreting the main program during its running. When the recycler works, the interpreter may change the access to an object affected by the recycler without affecting the running of the main program.
Gargage-collector API Lua provides some API interfaces for us to control the recycler: in C, use lua_gc:
int lua_gc(lua_State *L,int what,int data);
In Lua, use the collectgarbage function:
collectgarbage(what[ ,data])
Both functions provide the same function: What parameter indicates what to do, the operation is lua_gcstop ("stop"): Stop the recycler, until the "restart" parameter is used again to call collectgarbage (lua_gc); lua_gcrestart ("restart"): restart the recycler; lua_gccollect ("collect"): to execute a complete garbage collection cycle, ensure that all objects that fail to be accessed are recycled and finalized. This is the default colectgarbage operation; lua_gcstep ("Step"): executes garbage collection tasks. The number of jobs equals the amount of work that the recycler will do after data bytes are allocated; lua_gccount ("count"): returns the current memory used by Lua (in kilobytes ). This also includes the amount of memory that is not recycled. Lua_gccountb (not available): returns the amount of memory used by Lua (decimal part of kilobytes. Lua_gcsetpause ("setpause"): sets the pause parameter of the recycler. The unit of percentage is used. When the set data value is 100, 1 (100%) is set ). used to control the interval between two recycling cycles. Lua_gcsetstepmul ("setstepmul"): sets the step multiplier parameter of the recycler. It is also the unit of percentage. Controls the amount of memory to be recycled for each reclaim operation.
I have read this book. It is still difficult to read the technical books in English only. I still don't understand some technical concepts, because I have never been familiar with the Lua programming language before, it is a little difficult to directly read foreign books. I think it will be much easier to study later after reading this book.

Programming in Lua 3 Reading Notes (28th)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.