Lua C API 不适用于指针

Lua C API doesn't work with pointer

本文关键字:适用于 指针 不适用 API Lua      更新时间:2023-10-16

这就是我所做的。我在C++代码中创建了一个结构和一个静态函数

struct ItemDefinition {
  int64_t price;
};
int static getPrice(lua_State* L) {
  ItemDefinition* def = (ItemDefinition*)lua_touserdata(L, 1);
  printf("%pn", def);
  printf("%dn", def->price);
  return 0;
}

我还在lua中注册了该函数并初始化了一个ItemDefination对象。

ItemDefinition def;
def.price = 120;
lua_pushlightuserdata(lua_state_, (ItemDefinition*)&def);
lua_setglobal(lua_state_, "def");
luaL_Reg module[] = {{"getPrice", &getPrice}, {NULL, NULL}};

从我的 Lua 脚本中,我只是简单地调用函数

getPrice(def)

如果我只是打印出def的地址,如果工作正常。所以我确定该函数被成功调用。但是,如果我试图获得def->price,我会从地址清理器收到错误"==283789==ERROR stack use after return" 我不熟悉 c++ 和 lua。你能在问题所在提供帮助吗?

解决此问题,NVM。这实际上是因为指针问题。