将全局自定义数据移交给Lua实现的功能 [英] Hand over global custom data to Lua-implemented functions

查看:129
本文介绍了将全局自定义数据移交给Lua实现的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Lua应用程序中,我定义了一些自己的功能,这些功能已在lua_register("lua_fct_name","my_fct_name")中注册,以便Lua脚本知道这些功能.

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.

现在,我有一些需要在my_fct_name()中访问的自定义/用户数据.它只是指向我自己管理的内存区域的指针,因此我使用lua_pushlightuserdata (L,data)将其添加到Lua上下文中.

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.

现在看来我没有正确的位置来添加这些数据.创建L后立即完成操作后,我无法访问my_fct_name()中的数据,此处lua_touserdata(L,1)确实返回了NULL,因此在堆栈上不可用.在lua_pcall()执行脚本之前完成后,我收到有关意外数据的错误消息.

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.

那我必须在哪里/什么时候设置用户数据,以便在my_fct_name()中可用它们?

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

推荐答案

由于您拒绝提供代码,这完全没有帮助,因此让我举个例子.

Since you're refusing to provide your code, which is not helping at all, let me provide an example.

Lua状态(C端)的设置:

Setup of Lua state (C side):

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中,您将获得这样的指针,因为您将其作为参数提供了:

In the V1 you would get your pointer like this, since you provide it as an argument:

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

在V2中,您必须从globals表中获取它(这同样适用于V1)

In the V2, you would have to get it from the globals table (which would work for V1 as well)

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之间的交互基础来说应该足够了.

Have a look at the Lua Reference Manual and Programming in Lua. Mind you that the book that is available online is based on Lua 5.0, so it's not completely up to date, but should be sufficient for learning basics of interacting between C and Lua.

这篇关于将全局自定义数据移交给Lua实现的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆