LUA:垃圾收集用户数据+ [英] Lua: garbage collection + userdata

查看:100
本文介绍了LUA:垃圾收集用户数据+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下情况:

typedef struct rgb_t {float r,g,b} rbg_t;

// a function for allocating the rgb struct
rgb_t* rgb(r,g,b) {
 rgb_t* c = malloc(sizeof(rgb_t));
 c->r=r;
 c->g=g;
 c->b=b;
 return c;
}

// expose rgb creation to lua
int L_rgb (lua_State* L) {
 rgb_t** ud = (rgb_t **) lua_newuserdata(L, sizeof(rgb_t *));
 *ud = rgb(lua_tonumber(L,1),lua_tonumber(L,2),lua_tonumber(L,3));
 return 1;
}

当L_rgb功能从Lua叫了两个分配发生。 Lua的分配新的用户数据,为结构的RGB构造函数分配。当变量超出范围在Lua发生了用户数据变量是什么?如果垃圾回收发生了什么结构分配?

When the L_rgb function is called from Lua two allocations happen. Lua allocates new userdata and the rgb constructor function allocates for the struct. What happens to the userdata variable when the variable goes out of scope in Lua? If it is garbage collected what happens to the allocation of the struct?

推荐答案

您有两种方法来这种情况,都可以适用于您的具体情况。其他情况下,驱使你更加强烈,选择一个比其他。

You have two approaches to this situation, and both could apply to your specific case. Other cases drive you more strongly to choose one over the other.


  1. 为您的样品做你能做的,并使用的malloc(),让您的私人数据块,并存储指向它在全用户数据。如果你这样做,那么你必须设置在用户数据一元表,并使用其 __ GC 的元方法来释放分配块时,用户数据得到垃圾收集。

  1. You can do as you do in your sample, and use malloc() to get your private data block, and store a pointer to it in a full userdata. If you do this, then you must set a metatable on the userdata, and use its __gc metamethod to free the allocated block when the userdata gets garbage collected.

您可以使用用户数据本身作为分配您的私人数据块中,通过调用 lua_newuserdata函数()的malloc( )。在这种情况下,你不需要有一个 __ GC 元方法,因为Lua的将是直接管理分配的寿命。你可能还是希望有一个元表,这样就可以使用它的 __指数项创建一个名为成员的外观研究先按g b ,从你的结构检索它们的值。

You can use the userdata itself as the allocation for your private data block, by calling lua_newuserdata() in place of malloc(). In this case you do not need to have an __gc metamethod because Lua will be directly managing the lifetime of the allocation. You might still want to have a metatable so that you can use its __index entry to create the appearance of members named r, g, and b that retrieve their values from your struct.

无论哪种方式,你需要考虑的错误处理。

Either way, you need to think about error handling.

这篇关于LUA:垃圾收集用户数据+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆