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 孙世龙 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