How to change "arg" in Lua in C ++

test.lua

#! /usr/bin/env luajit

io.stdout:setvbuf('no')
for i = 1,#arg do
    io.write(arg[i] .. ' ')
end
io.write('\n')

If I run it on the command line

luajit test.lua

The error is not returned.

Here is my test.cpp

lua_State *l_= lua_open();
luaL_openlibs(l_);

luaJIT_setmode(l_, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
lua_pop(l_, 1);

int s = luaL_loadfile(l_, "test.lua");

lua_pushstring(l_, "arg1 arg2 arg3");
lua_setglobal(l_, "arg");

if (s == 0)
{
  s = lua_pcall(l_, 0, LUA_MULTRET, 0);
}

if (s != 0)
{
  std::cerr << "-- " << lua_tostring(l_, -1) << std::endl;
  lua_pop(l_, 1);  // remove error message
}

lua_close(l_);

However, when I run it, it is a PANIC error: an insecure error when calling the Lua API (/home/david/test.lua►: attempt to connect the nil value). How to solve this?

+4
source share
1 answer

You clicked a line arg.

But you expect tables arg in your code (and what is usual arg).

So, when you try argstr[i], you go nilback and explodes in concatenation.

Click the table correctly and your code should work.

+3
source

Source: https://habr.com/ru/post/1615672/


All Articles