Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pool allocator with lua GC #1855

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

takase1121
Copy link
Member

@takase1121 takase1121 commented Jul 9, 2024

This is the subset of #1854, specifically for the allocator.

Here's the description from luapool.h:

A simple pool allocator that can be used to allocate and free memory
using Lua's GC.

Create a lxl_pool with lxl_pcreate() and allocate memory using lxl_palloc(), lxl_pzero(), lxl_presize(), lxl_pcopy() and lxl_pstrdup(). You can free the memory with lxl_pfree(), but this is generally not needed. If you need to free the memory in a pool immediately, use lxl_pdestroy(). You must not use the pool after it has been destroyed.

We call setting the pool's lifetime as "pinning". When a pool is created, it is "pinned" to the stack slot that contains the "pool reference". A pool reference is the Lua object that manages the pool's lifetime. You can use pool->ref to get the stack index of the pool reference. Note that pool->ref is always the stack index, and this value will be invalid if you store the pool reference somewhere else (e.g. the Lua Registry). You can use lxl_pfromidx() to get a lxl_pool from an object in the stack. Finally, you can use pool->userdata to store extra data as a pointer.

Memory will not be freed immediately when the pool goes out of scope - it is subjected to the rules of Lua GC. There is no way to control this.

This is incredibly useful for those C Lua API functions, especially with process API, that allocates a bunch of data that has to be freed. To clarify, storing userdata like this is absolutely permitted by PUC Lua. Other implementations might need to look closer at this, but there's nothing stopping you from actually using malloc to allocate memory, save it to a list and free them with a finalizer attached to the pool reference. This is considered implementation-specific.

@takase1121
Copy link
Member Author

I am still thinking of how to test this code. It would be great if I have a tiny test suite.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant