简体   繁体   English

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

[英]LUA embeded in C++ socket.http [error: attempt to call a nil value]

Whene i run this code, get error当我运行此代码时,出现错误

[string "local http = require "socket.http"..."]:3: attempt to call a nil value (field 'request') [string "local http = require "socket.http"..."]:3: 尝试调用一个 nil 值(字段 'request')

How to resolve the problem?如何解决问题?

The C++ code 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;
}

The myLua.lua code myLua.lua 代码

local http = require "socket.http"

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

I believe the problem in your code is the following line:我相信您的代码中的问题是以下几行:

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

According to documentation it calls function luaopen_package and stores it's result in the table package.loaded["socket.http"] .根据文档,它调用函数luaopen_package并将其结果存储在表package.loaded["socket.http"] This is clearly not the right thing to do because when your code tries to explicitly load package "socket.http" with require "socket.http" it won't do it: the table entry for "socket.http" key is already taken by another package (namely, package ).这显然不是正确的做法,因为当您的代码尝试使用require "socket.http"显式加载包“socket.http”时,它不会这样做: "socket.http"键的表条目已经被占用由另一个包(即package )。

You should just remove this line to make it work.您应该删除此行以使其工作。

据说您的本地 http 变量为零,请尝试打印它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM