我如何从lua5.1(luajit)中从我的lua CFunction中拉出lightuserdata?

时间:2016-11-24 20:11:22

标签: c++ lua

我试图让lua直接触摸我的C ++端代码。我本质上想要一个不太可能做任何不必要的副本或增加不必要的性能开销的运行时控制器

现在我很难做到这一点,因为我似乎无法拉动我事先提供的指针......希望得到一些指导才能让这个工作......

#include <luajit-2.0/lua.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>

static int vpop (lua_State *L)
{
    std::vector<int> * ptr =  (std::vector<int> * )lua_touserdata(L,1); // im expecting to vec's address from main(), but alas, i get null
    std::cout << "pop ptr:" << ptr << "\n";

  return 0;
}

static int vpush (lua_State *L)
{
    std::vector<int> * ptr = (std::vector<int> * )lua_touserdata(L,1);
    std::cout << "push ptr:" << ptr << "\n";  return 1;
}
int main()
{
    std::vector<int> vec {0,1,2,3,4,5};
lua_State * L = lua_open();
luaL_openlibs(L);
static const luaL_reg Foo_methods[] = {
  {"vpop", vpop},
  {"vpush", vpush},
  {NULL,NULL}
};

luaL_register(L,"arr",Foo_methods);


lua_pushlightuserdata(L,&vec); // sending the address of the vector


if (luaL_dostring(L,"arr.vpop();"))
{
    printf("%s\n", lua_tostring(L, -1));
}



return 0;    

}

这是stdout

  

pop ptr:0

1 个答案:

答案 0 :(得分:2)

您没有将任何数据传递给arr.vpop()。你对代码有什么期望?:

arr.vpop()

在调用luaL_dostring()之前,无论你推送什么都没用,因为luaL_dostring()被定义为:

  

(luaL_loadstring(L,str)|| lua_pcall(L,0,LUA_MULTRET,0))

查看lua_pcall()的参数。将使用零参数。

即使您使用调整后的参数调用lua_pcall(),您的Lua代码仍然不会将任何参数传递给arr.vpop()。至少你应该使用vararg表达式传递chunk的参数:

arr.vpop(...)