Assume I have a pointer owned from the C-side, that I wish to push onto the Lua stack in the form of a userdata. What would be the best way to accomplish this, while not sacrificing the ability to specify a specific metatable?
My original idea was to use a light userdata, but from what I've read here, all light userdatas share a common metatable. This isn't desirable, as it would force common behavior for all of my c-sided objects.
Considering I desire to reuse metatables for Lua allocated objects, simply passing a different this pointer to the metamethods, my second idea involved attaching an artificial this pointer to userdata objects.
struct ud
{
struct T* ptr;
struct T data;
};
struct ud* p = (struct ud*)lua_newuserdata(L, sizeof(struct ud));
p->ptr = &(p->data);
Or, in the case of pushing a light userdata
struct T object;
struct T** p = (struct T**)lua_newuserdata(L, sizeof(struct T*));
*p = &object;
Is attaching a this pointer recommended, or is there a more API friendly alternative? My ultimate goal is simply to push an existing pointer to Lua, and associate a metatable with it in such a way that the metatable can be reused for both heavy and light userdatas.
void*
s. So what exactly do you want your first code example to do? – Nicol Bolas