lua-users home
lua-l archive

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


It was thus said that the Great Grzegorz Krasoń once stated:
> Function that returns nothing seems different than function that returns
> `nil`:
> 
> ```lua
> function f()
>     return nil
> end
> 
> function g()
> end
> 
> print(f()) -- prints nil
> print(g()) -- prints empty line
> ```
> 
> How to recognize this at the function call? For example how to implement an
> universal wrapper that would suppress all errors and still returns exactly
> the same thing as wrapped function in case of success?

  I can't say I'm surprised that no one mentioned a C solution.  It's
actually trivial in C:

#include <lua.h>
#include <lauxlib.h>

static int supress(lua_State *L)
{
  lua_pcall(L,lua_gettop(L)-1,LUA_MULTRET,0);
  return lua_gettop(L);
}

int luaopen_supress(lua_State *L)
{
  lua_pushcfunction(L,supress);
  return 1;
}

And the script:

supress = require "supress"

function f()
    return nil
end

function g()
end

function h(...)
  return ...
end

print(f()) -- prints nil
print(g()) -- prints empty line
print(h(1,2,3,4,5)) -- prints parameters

print(supress(f)) -- prints nil
print(supress(g)) -- prints empty line
print(supress(h,1,2,3,4,5)) -- prints parameters

prints the following:

nil

1       2       3       4       5
nil

1       2       3       4       5

  I think the question I have is "why?"  Why do you need such functionality? 
And what would you do when pcall() (or lua_pcall()) fails?

  -spc