4
votes

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

No error is 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 the error is PANIC: unprotected error in call to Lua API (/home/david/test.lua:5: attempt to concatenate a nil value). How to solve this?

1

1 Answers

3
votes

You've pushed an arg string.

But you are expecting an arg table in your code (and that's what arg is normally).

So when you try argstr[i] you get nil back and that explodes in the concatenation.

Push a table correctly and your code should work.