Lua C API: Push pointers as a userdata

Viewed 285

I have a pointer address which points to a userdata. I retrieved the address like so:

*(uint32_t*)lua_touserdata(L, -1)

Later on, I want to push that userdata back on top the stack by using the pointer. If this is possible, what must be done?

1 Answers

You could create a new user data after retrieving the pointer to the one you already created via lua_newuserdata(). Then set the underlying value of the pointer to the value of the underlying value of the first userdata. It should look something like this:

int *ud1 = lua_touserdata( L, -1 ); // Get userdata previously created

int *ud2 = lua_newuserdata( L, sizeof( int ) ); // Create new userdata
*ud2 = *ud1; // Set value of new userdata to the value of the previous userdata

// Userdata has been successfully "pushed"
assert(
        *( (int*) lua_touserdata( L, -1 ) ) == 
        *( (int*) lua_touserdata( L, -2 ) ) 
);
Related