add dict item

This commit is contained in:
Dmitriy Pleshevskiy 2022-11-18 22:46:17 +03:00
parent 3f0d252442
commit 7cd935026e
Signed by: pleshevskiy
GPG Key ID: 1B59187B161C0215
2 changed files with 29 additions and 15 deletions

34
lib.nix
View File

@ -3,10 +3,21 @@ let
inherit (builtins) concatStringsSep filter mapAttrs attrValues; inherit (builtins) concatStringsSep filter mapAttrs attrValues;
mkLuaNil = { _type = "nil"; }; mkLuaNil = { _type = "nil"; };
isLuaNil = val: isAttrs val && val ? _type && val._type == "nil"; isLuaNil = val: getType val == "nil";
mkDictItem = name: value: {
_type = "dict_item";
name = validString name;
value = toLua value;
};
isDictItem = val: getType val == "dict_item";
toLuaDictItem = name: value:
if isNull value then null
else "[${toLuaStr name}] = ${value}";
toLua = val: toLua = val:
if isLuaNil val then "nil" if isLuaNil val then "nil"
else if isDictItem val then toLuaDictItem val.name val.value
else if isAttrs val then toLuaDict val else if isAttrs val then toLuaDict val
else if isList val then toLuaList val else if isList val then toLuaList val
else if isString val then toLuaStr val else if isString val then toLuaStr val
@ -18,29 +29,24 @@ let
toLuaList = val: toLuaList = val:
wrapObj (excludeNull (map toLua val)); wrapObj (excludeNull (map toLua val));
toLuaDict = val: toLuaDict = val: toLua (attrValues (mapAttrs mkDictItem val));
let
toDictItem = name: value:
let luaValue = toLua value;
in
if isNull luaValue then null
else "[${toLuaStr name}] = ${luaValue}";
dictItems = excludeNull (attrValues (mapAttrs toDictItem val));
in
wrapObj dictItems;
excludeNull = val: filter (v: !(isNull v)) val; excludeNull = val: filter (v: !(isNull v)) val;
wrapObj = val: "{ ${concatStringsSep ", " val} }"; wrapObj = val: "{ ${concatStringsSep ", " val} }";
toLuaStr = val: "\"${val}\""; toLuaStr = val: "\"${validString val}\"";
toLuaBool = val: if val then "true" else "false"; toLuaBool = val: if val then "true" else "false";
getType = val: if isAttrs val && val ? _type then val._type else null;
validString = value:
if isString value then value
else throw "Value '${toString value}' is not a valid string";
in in
{ {
inherit toLua; inherit toLua;
inherit mkLuaNil; inherit mkLuaNil mkDictItem;
} }

View File

@ -2,7 +2,7 @@
let let
nix2lua = import ./lib.nix; nix2lua = import ./lib.nix;
inherit (nix2lua) toLua mkLuaNil; inherit (nix2lua) toLua mkLuaNil mkDictItem;
in in
pkgs.lib.runTests { pkgs.lib.runTests {
"test returns null" = { "test returns null" = {
@ -69,4 +69,12 @@ pkgs.lib.runTests {
}; };
expected = "{ [\"first\"] = { [\"second\"] = { [\"last\"] = \"hello\" } } }"; expected = "{ [\"first\"] = { [\"second\"] = { [\"last\"] = \"hello\" } } }";
}; };
"test returns array with dict items" = {
expr = toLua [
"foo"
(mkDictItem "foo" "hello")
10
];
expected = "{ \"foo\", [\"foo\"] = \"hello\", 10 }";
};
} }