lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi hackers,

Is it possible to create and use a userdata value, this way?

typedef struct MyItem {
   int size;
} MyItem;

typedef struct MyValue {
  const char * name;
  MyItem * item;
} MyValue;

static int lua_myvalue_new(lua_State *L) {
MyValue * value;
const char * name;
size_t l;
int n;

name = luaL_checklstring(L, 1, &l);
if (name == NULL) {
    return 0;
}
n = luaL_checkinteger(L, 2);
luaL_argcheck(L, n >= 1, 2, "invalid size");

value = (MyValue *) lua_newuserdata(L, sizeof(MyValue));
if (value == NULL) {
    return 0;
}
value->name = name;
luaL_getmetatable(L, MYVALUE_REGISTRY);
lua_setmetatable(L, -2);

value->item = (MyItem *) lua_newuserdata(L, sizeof(MyItem));
if (value->item == NULL) {
    return 0;
}
value->item->size = n;
luaL_getmetatable(L, UIMYITEM_REGISTRY);
lua_setmetatable(L, -2);

return 1; /* Must return value (MyValue) */
}

Howto return to Lua MyValue struct (userdata)?
MyItem needs to be allocated by malloc rather than lua_newuserdata?

best regards,
Ranier Vilela