Using the functions of standard Lua modules constantly returns Runtime error. Code example:

//... 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 definition of errors in lua.h, the number 2 corresponds to LUA_ERRRUN.

In this case, 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 result in 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)); //... 

Displays:

 0 Hello! 0 

How to use such functions? Thank!

  • Standard libraries loaded? - val
  • @val The fact is that when loading these standard libraries it gives the same error. For example, if I write "local myLib = require" io ", then it will crash on this line. - AccumPlus

1 answer 1

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

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

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

The fact is that C, before transferring the string somewhere, converts the control character \n to a newline and, on the Lua side, the code is as follows:

 io.write("Hello! ") 

What is syntactically incorrect construction.

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 .

This is what should end up:

 #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 downloaded the script from a file, then such an error would not have occurred and there is no double screening, of course, no need to do.

And finally, if you correctly handled the error, as was done in the example above, then it would not be difficult to google the decision on the error text.

  • Great answer! Thank! Last remark especially liked! - AccumPlus