Posted 20 June 2015 - 02:35 AM
I've been scratching my head about this for quite a while now, because I wanted to create a custom assert function that supported error levels.
It would be easy if it just would be basic calls like
But what really makes this troublesome is when you try to use functions that return multiple values, because if you use an error message and/or level then it only returns one value, that is, if the condition is true ofcourse, like in this example, where you can see the difference when only supplying the first argument( condition ) versus supplying all the arguments( condition, message, level ).
This what the assert_level function looks like
And this is the foo function, not really needed as it was used for testing purposes
So I'm basically wondering, is there a way to make this work? Or have I come to a dead end?
It would be easy if it just would be basic calls like
assert( 1 == 2, "one is not equal to two!", 0 )
But what really makes this troublesome is when you try to use functions that return multiple values, because if you use an error message and/or level then it only returns one value, that is, if the condition is true ofcourse, like in this example, where you can see the difference when only supplying the first argument( condition ) versus supplying all the arguments( condition, message, level ).
--# Without error level
local args = { assert_level( foo( true ) ) }
print( unpack( args ) ) --# Output: bar
--# With error message and level
local args = { assert_level( foo( true ), "failed to get values", 2 ) }
print( unpack( args ) ) --# Output: b failed to get values 2
I've figured out that's because when you pass a function call as the first argument, and it returns more than one value, those values gets overwritten by the arguments message and level that you pass onto the assert_level function, but I still haven't figured out how to solve this( if it's even possible )The code I'm using
You can find the original code here: http://lua.2524044.n...39p7645366.htmlThis what the assert_level function looks like
local assert_level = function( condition, message, level )
if not condition then
if type( message ) ~= "string" then
error( "string expected, got " .. type( message ), 2 )
elseif level and type( level ) ~= "number" then
error( "number expected, got " .. type( level ), 2 )
end
level = level == 0 and 0 or level == 1 and 1 or 2
error( message, level )
end
return condition, message, level
end
And this is the foo function, not really needed as it was used for testing purposes
local function foo( condition )
assert_level( type( condition ) == "boolean", "Must call foo() with a boolean", 2 )
local a, b, c = "b", "a", "r"
if condition then
return a, b, c
else
return nil, "an error message"
end
end
So I'm basically wondering, is there a way to make this work? Or have I come to a dead end?