Add when, unless

This commit is contained in:
madmaurice 2021-04-04 01:53:18 +02:00
parent 0b19227810
commit e163fdce59
3 changed files with 48 additions and 0 deletions

View file

@ -640,6 +640,44 @@ sub macro_cond {
} }
$macros{cond} = \&macro_cond; $macros{cond} = \&macro_cond;
sub macro_when {
my $ts = shift;
my $condition = parser_expr($ts);
my $work = parser_expr($ts);
return sub {
my $ctx = shift;
if ($condition->($ctx))
{
return $work->($ctx);
}
return undef;
}
}
$macros{when} = \&macro_when;
sub macro_unless {
my $ts = shift;
my $condition = parser_expr($ts);
my $work = parser_expr($ts);
return sub {
my $ctx = shift;
if (!$condition->($ctx))
{
return $work->($ctx);
}
return undef;
}
}
$macros{unless} = \&macro_unless;
sub compile { sub compile {
my ($term) = @_; my ($term) = @_;
my @tokens = tokenize($term); my @tokens = tokenize($term);

5
t/unless.t Normal file
View file

@ -0,0 +1,5 @@
(expect "unless - true condition"
(null (unless t 'fail)))
(expect "unless - false condition"
(equal 'ok (unless f 'ok)))

5
t/when.t Normal file
View file

@ -0,0 +1,5 @@
(expect "when - true condition"
(equal 'ok (when t 'ok)))
(expect "when - false condition"
(null (when f 'fail)))