lua-users home
lua-l archive

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


>What's wrong with error()?
Sorry for my poor English.
I would show you a simple example, please pay attention to the comments.

//C code.
int self_def_func(struct lua_State* L)
{
    int argc =  lua_gettop(L);

    int type = lua_type(L, 1);
    if(type != LUA_TNUMBER)
    {
         // I hope to tell the exact name of the parameter that passed
to the self-defined function.
        luaL_error(L, "the variable named XX should be a int or double");
    }
    else
    {
        double val = lua_tonumber(L, 1);
        if(var>100)
        {
              // I hope to tell the exact name of the parameter that
passed to the self-defined function.
              luaL_error(L, "the variable named XX is out of range");
        }
     }
  }

int main()
{
     ...
     lua_register(L,  self_def_func);
}

--lua code
temperature = 150;
loc = "test"
self_def_func(temperature, loc)

On Thu, Jan 21, 2021 at 11:48 AM Sean Conner <sean@conman.org> wrote:
>
> It was thus said that the Great 孙世龙 sunshilong once stated:
> > >what are you hoping to do with such information?
> > I want to give the users more accurate error message to accelerate the
> > debugging process.
> > For example, if the value provided by the user is out of range, I hope
> > to tell the user the variable named 'foo' is invalid(instead of
> > telling them the first or second parameter is invalid).
>
>   What's wrong with error()?
>
>         local function foo(x)
>           if x < 1 or x > 10 then
>             error('paramter "x" is out of range')
>           end
>
>           return x + 3
>         end
>
>         foo(0)
>
> [spc]lucy:/tmp>lua e.lua
> lua: e.lua:4: paramter "x" is out of range
> stack traceback:
>         [C]: in function 'error'
>         e.lua:4: in local 'foo'
>         e.lua:10: in main chunk
>         [C]: in ?
> [spc]lucy:/tmp>
>
> It shows which named parameter was invalid, plus the call stack showing
> where it was called in context.  If throwing an error is not to your liking,
> you could also do:
>
>         local function foo(x)
>           if x < 1 or x > 10 then
>             return nil,debug.traceback('parameter "x" is out of range')
>           end
>
>           return x + 3
>         end
>
> to mimic the common Lua idiom of returning nil plus an error message.
>
>   -spc