我收到一个函数作为另一个函数的参数,并想知道它的参数个数。这可能吗?
例如:
@function foo($list, $fn) {
if (number-of-arguments($fn) == 1) { // looking for this kinda magic
// ...
}
}
为了避免出现XY问题,如果无法解决上述问题,我尝试做的就是忽略call
的错误并提供额外的参数:{{1如果call($fn, $arg1, $arg2)
被定义为只接受一个参数,则会失败。目前它失败了:$fn
。我也希望尝试使用try / catch机制,但Sass中也没有这样的概念。
答案 0 :(得分:1)
没有内省功能,但您可以执行基于地图的验证,如:
// dummy functions
@function fn1($a){ @return $a; }
@function fn2($a, $b){ @return $a + $b; }
@function fn3($a, $b, $c){ @return $a + $b + $c; }
@function foo(
$fn, // function name as string
$args... // arglist
){
// arguments passed
$args-passed: length($args);
// arguments required by functions
$args-required: map-get((
fn1: 1, // fn1 takes 1 argument
fn2: 2, // fn2 takes 2 arguments
fn3: 3 // fn3 takes 3 arguments
), $fn);
// match => make call
// no match => throw warning or error or do something else
@if $args-passed == $args-required {
@return call($fn, $args...);
} @else {
@warn 'function `#{$fn}` requires #{$args-required} arguments #{$args-passed} were passed ';
@return null;
}
}
test {
value-1: foo(fn1, 1);
value-2: foo(fn2, 1, 2);
value-3: foo(fn3, 1, 2);
}
输出:
test {
value-1: 1;
value-2: 3;
// value-3 receives null and is not printed but a warning is thrown
// "function `fn3` requires 3 arguments 2 were passed"
}