LUA 嵌入 C++ 中的 socket.http [错误:尝试调用空值]

运行代码时出现错误 **

[string "local http = require "socket.http"..."]:3: 尝试调用 空值(字段‘request’)

如何解决问题?

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",
}
点赞
用户4363754
用户4363754

它在说你本地的 http 变量为空。 尝试打印它。

2018-10-22 20:45:20
用户1492351
用户1492351

我认为你代码中的问题在于以下这行:

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

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

你应该只需要删除这一行即可。

2018-10-22 20:51:28