0

Within my Lua-application I have some own functions defined that are registered with lua_register("lua_fct_name","my_fct_name") so that they are known to the Lua script.

Now I have some custom/user data that need to be accessible within my_fct_name(). It is just a pointer to a memory area I manage for my own so I use lua_pushlightuserdata (L,data) to add it to Lua-context.

Now it seems I don't have the correct position to add these data. When done right after L was created I can't access the data in my_fct_name(), here lua_touserdata(L,1) does return NULL, so it is not available on the stack. When done right before lua_pcall() executes the script, I get an error message about unexpected data.

So where/when do I have to set my user data so that they are available within my_fct_name()?

4

1 回答 1

3

由于您拒绝提供您的代码,这根本没有帮助,让我提供一个示例。

Lua 状态的设置(C 端):

lua_State *L = luaL_newstate();

//Set your userdata as a global
lua_pushlightuserdata(L, mypointer);
lua_setglobal(L, "mypointer");

//Setup my function
lua_pushcfunction(L, my_fct_name);
lua_setglobal(L, "my_fct_name");

//Load your script - luaScript is a null terminated const char* buffer with my script
luaL_loadstring(L, luaScript);

//Call the script (no error handling)
lua_pcall(L, 0, 0, 0);

Lua代码V1:

my_fct_name(mypointer)

Lua代码V2:

my_fct_name()

在 V1 中,您会得到这样的指针,因为您将它作为参数提供:

int my_fct_name(lua_State *L)
{
    void *myPtr = lua_touserdata(L, 1);
    //Do some stuff
    return 0;
}

在 V2 中,您必须从全局表中获取它(这也适用于 V1)

int my_fct_name(lua_State *L)
{
    lua_getglobal(L, "mypointer");
    void *myPtr = lua_touserdata(L, -1);  //Get it from the top of the stack
    //Do some stuff
    return 0;
}

查看Lua 参考手册Lua 编程。请注意,网上提供的这本书是基于 Lua 5.0 的,所以它不是完全最新的,但对于学习 C 和 Lua 之间交互的基础知识应该足够了。

于 2013-05-23T13:30:52.733 回答