前置知识: Lua

用户数据

1 minAdvanced2026/6/14

Lua用户数据详解:userdata扩展C类型。

1. 轻量用户数据

// 存储指针,无元表
void *ptr = some_pointer;
lua_pushlightuserdata(L, ptr);

2. 完整用户数据

typedef struct {
    double x, y;
} Point;

// 创建
Point *p = (Point *)lua_newuserdata(L, sizeof(Point));
p->x = 1.0;
p->y = 2.0;

// 设置元表
luaL_getmetatable(L, "Point");
lua_setmetatable(L, -2);

3. 注册元表

static int point_getx(lua_State *L) {
    Point *p = (Point *)luaL_checkudata(L, 1, "Point");
    lua_pushnumber(L, p->x);
    return 1;
}

static const luaL_Reg point_methods[] = {
    {"getx", point_getx},
    {NULL, NULL}
};

// 注册
luaL_newmetatable(L, "Point");
luaL_setfuncs(L, point_methods, 0);
lua_setfield(L, -2, "__index");