lua-users home
lua-l archive

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

Bruno Silva wrote:
> I have a newbie question then: how should I call this function in an
> *error-proof* way?
>         -- takes 2 strings, returns a boolean
>         handled = Function (arg1, arg2)
>         // calls Function
>         lua_getglobal(s_lua, "Function");
>         lua_pushstring (s_lua, arg1);
>         lua_pushstring (s_lua, arg2);
>         if (lua_call (s_lua, 2, 1) == 0)
>         {
>             handled = (bool) lua_tonumber (s_lua, -1);
>             lua_pop (s_lua, 1);
>         }

That is difficult.  lua_getglobal, lua_pushstring and lua_tonumber
may raise an error.  Even lua_pushcfunction/cclosure may raise one
so it's pretty difficult to call something in a secure way.  A
lua_catch function (similar to luaD_runprotected) would help a lot.

> This must work (i.e., leave a clean stack) regardless of what "Function"
> evaluates to and whether the execution of "Function" succeeded or failed
> for whatever reasons. Is it guaranteed to push a value if it succeeds (I
> believe the docs say so)?

If the return value of lua_call is 0 you get exactly the number of results
you say you want (3rd arg).  If the function returns less, nils are pushed.

> Is it guaranteed to not leave anything on the stack if it fails (couldn't
> find this in the docs)?

If lua_call returns != 0 it removes the function, its arguments and every-
thing above from the stack so that it is clean afterwards.

Ciao, ET.