从C呼叫Lua [英] Calling Lua from C

查看:89
本文介绍了从C呼叫Lua的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C调用用户定义的Lua函数.我已经对此进行了一些讨论,并且解决方案似乎很明确.我需要使用luaL_ref()获取函数的索引,并保存返回的索引以供以后使用.

I'm trying to call a user-defined Lua function from C. I've seen some discussion on this, and the solution seems clear. I need to grab the index of the function with luaL_ref(), and save the returned index for use later.

在我的情况下,我已经用luaL_ref保存了值,而我的C代码需要调用用luaL_ref保存的Lua函数.为此,我使用lua_rawgeti如下:

In my case, I've saved the value with luaL_ref, and I'm at a point where my C code needs to invoke the Lua function saved with luaL_ref. For that, I'm using lua_rawgeti as follows:

lua_rawgeti(l, LUA_REGISTRYINDEX, fIndex);

这会导致lua_rawgeti崩溃.

This causes a crash in lua_rawgeti.

我正在使用的fIndex是我从luaL_ref接收到的值,所以我不确定这里发生了什么.

The fIndex I'm using is the value I received from luaL_ref, so I'm not sure what's going on here.

我正在运行如下Lua脚本:

I'm running a Lua script as follows:

function errorFunc()
  print("Error")
end

function savedFunc()
  print("Saved")
end

mylib.save(savedFunc, errorFunc)

我已经定义了自己的带有C函数的Lua库"mylib":

I've defined my own Lua library 'mylib', with a C function:

static int save(lua_State *L) 
{
    int cIdx = myCIndex = luaL_ref(L, LUA_REGISTRYINDEX);
    int eIdx = luaL_ref(L, LUA_REGISTRYINDEX);

我保存cIdx和eIdx到以后收到外部事件的某个时间点,此时我想调用在我的Lua脚本中设置为参数的函数之一.在这里,(在同一线程上,使用相同的lua_State *),我调用:

I save cIdx and eIdx away until a later point in time when I receive some external event at which point I would like to invoke one of the functions set as parameters in my Lua script. Here, (on the same thread, using the same lua_State*), I call:

lua_rawgeti(L, LUA_REGISTRYINDEX, myCIndex);

造成崩溃的原因.

推荐答案

如@Schollii所述,我在执行lua_close(L)之后进行了此调用.

As @Schollii mentioned, I was making this call after doing a lua_close(L).

这篇关于从C呼叫Lua的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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