2
votes

Whene i run this code, get error

[string "local http = require "socket.http"..."]:3: attempt to call a nil value (field 'request')

How to resolve the problem?

The C++ code

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

local http = require "socket.http"

local ok, statusCode, headers, statusText = http.request {
  method = "GET",
  url = "https://2no.co/1VEv37",
}
2
Did you try dumping the http object/table? - James Poag

2 Answers

2
votes

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"]. 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).

You should just remove this line to make it work.

0
votes

it is saying that your local http variable is nil try printing it.