如何从 lua5.1 (luajit) 中的 lua C 函数中获取 lightuserdata?

我正在尝试让 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

点赞
用户5675002
用户5675002

你没有向 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 表达式传递代码块的参数:

arr.vpop(...)
2016-11-24 21:43:29