Accessing Light userdata in Lua
Asked Answered
K

2

3

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?

Katiakatie answered 10/6, 2011 at 14:57 Comment(1)
If you are wanting to manipulate the object on the Lua side, you may be better served using userdata rather than light userdata. I wrote a long answer for doing this by hand in c++ here : #3482356 Alternatively you could use lua bind.Overabundance
B
11

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.

Birkle answered 10/6, 2011 at 16:17 Comment(0)
P
1

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;
};
Pohai answered 10/6, 2011 at 15:3 Comment(1)
But what about 'reading data' for something like, "If x > 5, then y = -x?" Would all instances of data interaction require their own C++ functions that can either change or return data?Katiakatie

© 2022 - 2024 — McMap. All rights reserved.