Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua C API: Push pointers as a userdata

Tags:

c

lua

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?

like image 564
Burner Dev Avatar asked Jun 05 '26 16:06

Burner Dev


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 ) ) 
);
like image 124
Caleb Loera Avatar answered Jun 07 '26 08:06

Caleb Loera