add IO functions

This commit is contained in:
Pekka Laiho 2020-06-03 19:57:58 +07:00
parent e1298ba5ec
commit c633d39b07
2 changed files with 35 additions and 0 deletions

View File

@ -19,6 +19,7 @@ function ml_get_lisp(): array
// Register libraries
(new MadLisp\Lib\Collections())->register($env);
(new MadLisp\Lib\Compare())->register($env);
(new MadLisp\Lib\IO())->register($env);
(new MadLisp\Lib\Math())->register($env);
(new MadLisp\Lib\Strings())->register($env);
(new MadLisp\Lib\Time())->register($env);

34
src/Lib/IO.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace MadLisp\Lib;
use MadLisp\CoreFunc;
use MadLisp\Env;
class IO implements ILib
{
public function register(Env $env): void
{
$env->set('file?', new CoreFunc('file?', 'Check if file exists.', 1, 1,
fn (string $filename) => file_exists($filename)
));
$env->set('fread', new CoreFunc('fread', 'Read contents of a file.', 1, 1,
function (string $filename) {
return @file_get_contents($filename);
}
));
$env->set('fwrite', new CoreFunc('fwrite', 'Write string (second argument) to file (first argument). Give true as optional third argument to append instead of overwrite.', 2, 3,
function (string $filename, $data, $append = false) {
$flags = 0;
if ($append) {
$flags = \FILE_APPEND;
}
$result = @file_put_contents($filename, $data, $flags);
return $result !== false;
}
));
}
}