add local and func

This commit is contained in:
Dmitriy Pleshevskiy 2024-04-17 14:55:12 +03:00
parent 190a991b02
commit 176026c58d
Signed by: pleshevskiy
GPG key ID: 17041163DA10A9A2
2 changed files with 53 additions and 23 deletions

58
lib.nix
View file

@ -49,6 +49,27 @@ let
++ [ (raw "") ]
);
pipe = join ".";
spaceBetween = join " ";
op = operation: left: right: concat [ (raw "(") (join " ${operation} " [ left right ]) (raw ")") ];
add = op "+";
sub = op "-";
mul = op "*";
div = op "/";
mod = op "%";
exp = op "^";
eq = op "==";
ne = op "~=";
gt = op ">";
lt = op "<";
gte = op ">=";
lte = op "<=";
and = op "and";
or = op "or";
not = expr: spaceBetween [ (raw "not") expr ];
isRaw = expr: getType expr == "raw";
raw = expr:
@ -72,28 +93,21 @@ let
);
require = name: call "require" [ name ];
local = expr: spaceBetween [ (raw "local") expr ];
set = variable: value: join " = " [ (raw variable) value ];
lset = variable: value: join " " [ (raw "local") (set variable value) ];
op = operation: left: right: concat [ (raw "(") (join " ${operation} " [ left right ]) (raw ")") ];
add = op "+";
sub = op "-";
mul = op "*";
div = op "/";
mod = op "%";
exp = op "^";
eq = op "==";
ne = op "~=";
gt = op ">";
lt = op "<";
gte = op ">=";
lte = op "<=";
and = op "and";
or = op "or";
not = expr: join " " [ (raw "not") expr ];
func = name: params: body:
(concatLines
([
(concat [
(spaceBetween (map raw [ "function" name ]))
(raw "(")
(join ", " (map raw params))
(raw ")")
])
]
++ body
++ [ (raw "end") ])
);
isLuaNil = expr: getType expr == "nil";
LuaNil = { _type = "nil"; };
@ -148,7 +162,7 @@ in
inherit LuaNil;
inherit raw join concat concatLines pipe;
inherit namedField call require set lset;
inherit namedField call require local set func;
inherit op;
inherit eq ne gt lt gte lte;

View file

@ -145,7 +145,7 @@ with nix2lua; pkgs.lib.runTests {
expected = "parser_config.d2 = { }";
};
"test returns lua with setting value to the local variable" = {
expr = toLua (lset "parser_config.d2" { });
expr = toLua (local (set "parser_config.d2" { }));
expected = "local parser_config.d2 = { }";
};
"test returns all operations" = {
@ -162,4 +162,20 @@ with nix2lua; pkgs.lib.runTests {
(10 > 5)
'';
};
"test returns defined function" = {
expr = toLua (func "hello" [ "a" "b" ] [
(eq (mul (add (var "a") 2) (sub 2 1)) 3)
(not (eq (mul (add (var "b") 2) (sub 2 1)) 3))
(not 10)
(gt 10 5)
]);
expected = ''
function hello(a, b)
(((a + 2) * (2 - 1)) == 3)
not (((b + 2) * (2 - 1)) == 3)
not 10
(10 > 5)
end
'';
};
}