Output the type that was incorrect to make it more obvious what the user is doing wrong without them adding logging. To avoid string building during lots of vector math, introduced a private precond module that only builds the strings when an error occurs. It uses error() to put the resulting error message at the caller to cpml. Before: lua: ~/cpml/modules/vec2.lua:52: new: Wrong argument type for x (<number> expected) lua: ~/cpml/modules/vec2.lua:424: __add: Wrong argument type for right hand operand. (<cpml.vec2> expected) example stack traceback: [C]: in function 'assert' ~/cpml/modules/vec2.lua:424: in metamethod '__add' test_cpml.lua:32: in main chunk [C]: in ? After: lua: test_cpml.lua:31: new: Wrong argument type for x: string (<number> expected) lua: test_cpml.lua:32: __add: Wrong argument type 'string' for right hand operand. (<cpml.vec2> expected) example stack traceback: [C]: in function 'error' ~/cpml/modules/_private_precond.lua:13: in function 'modules._private_precond.assert' ~/cpml/modules/vec2.lua:425: in metamethod '__add' test_cpml.lua:32: in main chunk [C]: in ? The tracebacks are longer, but the initial error is at the location of the mistake and the output includes the input type.
18 lines
320 B
Lua
18 lines
320 B
Lua
-- Preconditions for cpml functions.
|
|
local precond = {}
|
|
|
|
|
|
function precond.typeof(t, expected, msg)
|
|
if type(t) ~= expected then
|
|
error(("%s: %s (<%s> expected)"):format(msg, type(t), expected), 3)
|
|
end
|
|
end
|
|
|
|
function precond.assert(cond, msg, ...)
|
|
if not cond then
|
|
error(msg:format(...), 3)
|
|
end
|
|
end
|
|
|
|
return precond
|