| 1 | local libraryUtil = {} |
| 2 | |
| 3 | function libraryUtil.checkType( name, argIdx, arg, expectType, nilOk ) |
| 4 | if arg == nil and nilOk then |
| 5 | return |
| 6 | end |
| 7 | if type( arg ) ~= expectType then |
| 8 | local msg = string.format( "bad argument #%d to '%s' (%s expected, got %s)", |
| 9 | argIdx, name, expectType, type( arg ) |
| 10 | ) |
| 11 | error( msg, 3 ) |
| 12 | end |
| 13 | end |
| 14 | |
| 15 | function libraryUtil.checkTypeMulti( name, argIdx, arg, expectTypes ) |
| 16 | local argType = type( arg ) |
| 17 | for _, expectType in ipairs( expectTypes ) do |
| 18 | if argType == expectType then |
| 19 | return |
| 20 | end |
| 21 | end |
| 22 | local n = #expectTypes |
| 23 | local typeList |
| 24 | if n > 1 then |
| 25 | typeList = table.concat( expectTypes, ', ', 1, n - 1 ) .. ' or ' .. expectTypes[n] |
| 26 | else |
| 27 | typeList = expectTypes[1] |
| 28 | end |
| 29 | local msg = string.format( "bad argument #%d to '%s' (%s expected, got %s)", |
| 30 | argIdx, |
| 31 | name, |
| 32 | typeList, |
| 33 | type( arg ) |
| 34 | ) |
| 35 | error( msg, 3 ) |
| 36 | end |
| 37 | |
| 38 | function libraryUtil.checkTypeForIndex( index, value, expectType ) |
| 39 | if type( value ) ~= expectType then |
| 40 | local msg = string.format( "value for index '%s' must be %s, %s given", |
| 41 | index, expectType, type( value ) |
| 42 | ) |
| 43 | error( msg, 3 ) |
| 44 | end |
| 45 | end |
| 46 | |
| 47 | function libraryUtil.checkTypeForNamedArg( name, argName, arg, expectType, nilOk ) |
| 48 | if arg == nil and nilOk then |
| 49 | return |
| 50 | end |
| 51 | if type( arg ) ~= expectType then |
| 52 | local msg = string.format( "bad named argument %s to '%s' (%s expected, got %s)", |
| 53 | argName, name, expectType, type( arg ) |
| 54 | ) |
| 55 | error( msg, 3 ) |
| 56 | end |
| 57 | end |
| 58 | |
| 59 | function libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc ) |
| 60 | return function ( self, method ) |
| 61 | if self ~= selfObj then |
| 62 | error( string.format( |
| 63 | "%s: invalid %s. Did you call %s with a dot instead of a colon, i.e. " .. |
| 64 | "%s.%s() instead of %s:%s()?", |
| 65 | libraryName, selfObjDesc, method, varName, method, varName, method |
| 66 | ), 3 ) |
| 67 | end |
| 68 | end |
| 69 | end |
| 70 | |
| 71 | return libraryUtil |