Question

I may be misunderstanding their use or misread the documentation, but how do I access members of a struct or class passed to Lua as light userdata? For example if a vector using the following struct

typedef struct Foo {
  int x;
  int y;
} Foo;

was declared as 'test' and defined as something like x = 413 and y = 612, and pushed with a call

lua_pushlightuserdata( L, (void *) &test ) ;

What would the Lua code of a function that manipulates or prints x and y look like?

Was it helpful?

Solution

Light userdata in Lua is just a pointer. Lua has no understanding of how to read the contents of the object referenced by the pointer. The purpose of this data is to allow one C API call to pass a reference to another API call.

If you want to work with data in Lua, you need to push it onto the stack, and in your case I'd make it a table. If you need this data synchronized between C and Lua, then you'll need to write functions in both sides to handle the assignment and copy the value to the other environment. The other option is to only have the data in Lua and retrieve it via a Lua API when in C, or to have it in C and retrieve it via a C API (that you would create) when in Lua.

For more information, Programming in Lua and the Lua-users Wiki each have brief descriptions.

OTHER TIPS

Nothing. You can't access or do anything with userdata of any sort from Lua. You must provide C++ functions for all manipulation. Of course, this can be made easier through the correct use of metafunctions.

Oh, and you don't need that typedef struct crap in C++. You can just say

struct Foo {
    int x;
    int y;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top