improve function api

This commit is contained in:
Dmitriy Pleshevskiy 2024-04-20 17:36:34 +03:00
parent 4d3872b704
commit f3796d29b4
Signed by: pleshevskiy
GPG key ID: 17041163DA10A9A2
2 changed files with 17 additions and 9 deletions

20
lib.nix
View file

@ -75,8 +75,8 @@ let
call = fnName: args:
concat [ (validFuncName fnName) (wrapParen (join ", " args)) ];
call0 = call [ ];
call1 = arg: call [ arg ];
call0 = fnName: call fnName [ ];
call1 = fnName: arg: call fnName [ arg ];
require = name: call1 "require" name;
kw_and = raw "and";
@ -119,20 +119,24 @@ let
local = expr: spaceBetween [ kw_local expr ];
set = variable: value: join " = " [ (raw variable) value ];
func' = fnName: params: body:
(spaceBetween
func = fnName: params: body:
let
f =
if isList body then concatLines
else if isAttrs body then spaceBetween
else error "Value ${toString body} is not a valid function body";
in
(f
([
(concat [
(spaceBetween [ kw_function (validFuncName fnName) ])
(wrapParen (join ", " (map raw params)))
])
]
++ body
++ (if isList body then body else if isAttrs body then [ body ] else [ ])
++ [ kw_end ])
);
func = fnName: params: body:
func' fnName params (concatLines body);
lambda = func' "";
lambda = func "";
lambda0 = lambda [ ];
return = expr: spaceBetween ([ kw_return expr ]);

View file

@ -168,7 +168,7 @@ with nix2lua; pkgs.lib.runTests {
);
expected = "name = ((a >= 1) and (a <= 10))";
};
"test returns defined function" = {
"test returns defined multiline 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))
@ -184,6 +184,10 @@ with nix2lua; pkgs.lib.runTests {
end
'';
};
"test returns defined singleline function" = {
expr = toLua (func "hello" [ "a" ] (call1 "h.world" (var "a")));
expected = "function hello(a) h.world(a) end";
};
"test returns if statement" = {
expr = toLua (if' (eq 10 10) [
(call "print" [ 10 ])