Accessing Light userdata in Lua

≡放荡痞女 提交于 2019-12-12 21:09:35

问题


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?


回答1:


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.




回答2:


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;
};


来源:https://stackoverflow.com/questions/6308135/accessing-light-userdata-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!