lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Mar 29, 2010 at 10:22 AM, Roberto Ierusalimschy wrote:
> In 5.2, luaL_cpcall is able to return values. Doesn't that solve
> the problem? (luaL_cpcall is also cheaper than 5.1's lua_cpcall.)

Under Lua 5.2.0work3, we can make this example error safe without too
much trouble:

  /* implement common utility function ppushstring (protected push string) */
  static int pushudstring(lua_State * L) {
     lua_pushstring(L, (char const *)lua_touserdata(L, 1));
     return 1;
  }
  static int ppushstring(lua_State * L, char const * str) {
    lua_pushcfunction(L, &pushudstring);
    lua_pushlightuserdata(L, str);
    return lua_pcall(L, 1, 1, 0);
  }

  /* now solve the real problem: migrate C heap object to Lua stack object */
  char const * const str = some_library_get_string(); /* alloc C
string or return NULL */
  int const err = ppushstring(L, str); /* push Lua string (or nil
given NULL) or return error code while pushing Lua error */
  some_library_free_string(str);
  if (err != 0) lua_error(L);
  /* note: Lua string alone exists now */

Perhaps in this case we would prefer this actually:

  lua_freezeerror(L);  // begin queuing any errors
  char const * const str = some_library_get_string();
  lua_pushstring(L, str);
  some_library_free_string(str);
  lua_thawerror(L);  // stop queuing errors, clear queue, and raise
first queued error if any