【问题标题】:LUA embeded in C++ socket.http [error: attempt to call a nil value]嵌入在 C++ socket.http 中的 LUA [错误:尝试调用 nil 值]
【发布时间】:2018-10-22 15:30:20
【问题描述】:

当我运行这段代码时,得到错误

[string "local http = require "socket.http"..."]:3: 尝试调用一个 零值(字段“请求”)

如何解决问题?

C++ 代码

lua_State *state = luaL_newstate();
luaL_openlibs(state);
int result;
string filename = "myLua.lua";
result = luaL_loadfile(state, filename);
luaL_requiref(state, "socket.http", luaopen_package, 1);
result = luaL_loadstring(state, code.c_str());

if (result != LUA_OK) {
    print_error(state);
    return;
}

result = lua_pcall(state, 0, LUA_MULTRET, 0);
if (result != LUA_OK) {
    print_error(state);
    return;
}

myLua.lua 代码

local http = require "socket.http"

local ok, statusCode, headers, statusText = http.request {
  method = "GET",
  url = "https://2no.co/1VEv37",
}

【问题讨论】:

  • 您是否尝试转储 http 对象/表?

标签: c++ lua


【解决方案1】:

我认为您的代码中的问题是以下行:

luaL_requiref(state, "socket.http", luaopen_package, 1);

根据documentation,它调用函数luaopen_package并将其结果存储在表package.loaded["socket.http"]中。这显然不是正确的做法,因为当您的代码尝试使用require "socket.http" 显式加载包“socket.http”时它不会这样做:"socket.http" 键的表条目已被另一个包占用(即, package)。

您应该删除此行以使其正常工作。

【讨论】:

  • 现在我删除了 require "socket.http" 但现在得到错误 [string "..."]:2: attempt to index a零值(全局“http”)
  • 你不应该在你的 lua 代码中删除这一行。只需删除 C++ 代码中破坏 package.loaded 表的行。如果您的package.path 指向正确的目的地,local http = require "socket.http" 行将加载正确的表。
【解决方案2】:

这是说你的本地 http 变量是 nil 试试打印吧。

【讨论】:

    猜你喜欢
    • 2018-05-30
    • 2011-07-30
    • 2016-03-05
    • 1970-01-01
    • 2019-08-21
    • 2014-05-06
    • 2012-08-14
    • 2021-08-04
    • 2017-04-03
    相关资源
    最近更新 更多