LUA lib + C language, using module functions returns runtime error

Using the functions of standard Lua modules constantly returns a Runtime error. Sample code:

//...
char script[] = "io.write(\"Hello!\n\")";
printf("%d\n", luaL_loadbuffer(L, script, strlen(script), NULL));
printf("%d\n", lua_pcall(L, 0, 0, 0));
//...

The screen displays:

0
2

According to the error definition in lua. h, the number 2 corresponds to LUA_ERRRUN.

At the same time, the same line works in the terminal:

$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> io.write("Hello!\n");
Hello!

Using standard lua elements does not cause an error:

//...
char script[] = "print(\"Hello!\")";
printf("%d\n", luaL_loadbuffer(L, script, strlen(script), NULL));
printf("%d\n", lua_pcall(L, 0, 0, 0));
//...

Outputs:

0
Hello!
0

How to use such functions correctly? Thanks!

 1
Author: AccumPlus, 2016-08-23

1 answers

To get the error message in a readable form, you can use the function lua_tostring and for your example, it should report:

[string "io.write("Hello!..."]:1: unfinished string near '"Hello!'

This message indicates that Lua found an incomplete string on its side.

The fact is that C, before passing a string anywhere, converts the control character \n to a line feed and on the side of Lua the code is obtained as follows:

io.write("Hello!
")

Which is a syntactically incorrect construction.

To to avoid this error, you need to make sure that C does not interfere and does not spoil the string. This is done by double escaping the control character: \\n.

Here's what should happen in the end:

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main (void) {

  char script[] = "io.write(\"Hello!\\n\")";

  lua_State *L = luaL_newstate();   /* открывает Lua */
  luaL_openlibs(L);                 /* открывает стандартные библиотеки */

  int error = luaL_loadstring(L, script) || lua_pcall(L, 0, 0, 0);

  if (error) {
    fprintf(stderr, "%s\n", lua_tostring(L, -1));
    lua_pop(L, 1);  /* снять сообщение об ошибке со стека */
  }

  lua_close(L);  /* закрывает Lua */

  return 0;
}

If you were loading the script from a file, then such an error would not occur and there is no double escaping, of course, you do not need to do it.

And finally, if you correctly handled the error, as it is done in the example above, then Google the solution for the error text, do not it would be difficult.

 5
Author: zed, 2016-08-25 13:03:26