3

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
  • If you want to store a reference to a userdatum so you can push it back onto the Lua stack at a later time, I suggest using the functions luaL_ref and luaL_unref. Commented Apr 6, 2020 at 3:16

1 Answer 1

1

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 ) ) 
);
Sign up to request clarification or add additional context in comments.

2 Comments

The assert passes for me. Am I incorrect to assume that I could continue adding to the stack after "*ud2 = *ud1;"? E.g lua_getfield(-1, "field")
Yes you are correct. What was done in the example I gave will not keep you from adding to the stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.