User data

Lua has a special data type called userdata. Userdata can store arbitrary C data structures as Lua data—it's just some arbitrary amount of memory. Userdata can have meta tables, which enables us to extend the type using the same mechanism we would use to extend tables. Like tables, userdata is compared by reference, not by value.

To create a new block of userdata memory, use the void* lua_newuserdata (lua_State*, size_t) function. The first argument of this function is the Lua state to work on, and the second argument is the number of bytes to reserve for user data. The function returns a pointer to the block of memory that Lua has reserved for this user data.

A three-dimensional vector might be stored in userdata like as follows:

struck Vec3 {
float x, y, z;
}

int make_up_vector(lua_State *L) {
Vec3* newVec = (Vev3*)lua_newuserdata(L, sizeof(Vec3));
newVec->x = 0;
newVec->y = 1;
newVec->z = 0;
// The new user data is on the stack
return 1;
}

User data can be retrieved using the lua_touserdata function. This function returns a pointer to the user data memory. It's first argument is the Lua state to work on, and the second argument is the index on the stack at which the user data is expected to be. If you modify the pointer returned by the user data, you are modifying the actual value of the user data. The following code sample shows how to use the lua_touserdata function:

int lua_vec3_cross (lua_State *L) {
Vec3* a = (Vec3*)lua_touserdata(L, -2);
Vec3* b = (Vec3*)lua_touserdata(L, -1);

float dot = a->x * b->x + a->y * b->y + a->z * b->z;
lua_pushnumber(L, dot);

return 1;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.43.26