Zhen
Zhen

Reputation: 4283

Is there a Lua Warning instead of Lua Error?

Lua has the luaL_error, and lua_error functions to be used inside a C function, like:

luaL_error( L, "something bad" );

This will cause that a error message was show and Lua execution halted. The error message will contain the line and file where it occurs:

Error: ../example/ex01.lua:6: something bad

Is there a similar function that shows the error but don't break the lua execution? but showing the line where it occurs.

Upvotes: 7

Views: 3511

Answers (1)

lhf
lhf

Reputation: 72312

Copy the source code of luaL_error and replace the call to lua_error at the end by a suitable call to printf using the string lua_tostring(L,-1). Something like this:

LUALIB_API int luaL_warn (lua_State *L, const char *fmt, ...) {
  va_list argp;
  va_start(argp, fmt);
  luaL_where(L, 1);
  lua_pushvfstring(L, fmt, argp);
  va_end(argp);
  lua_concat(L, 2);
  printf("warning: %s\n",lua_tostring(L,-1));
  return 0;
}

static int luaB_warn (lua_State *L) {
      return luaL_warn(L, "%s", luaL_checkstring(L, 1));
}

Don't forget to export it to Lua by adding an entry in say base_funcs in lbaselib.c or by calling lua_register(L,"warn",luaB_warn).

Upvotes: 5

Related Questions