add dict item
This commit is contained in:
parent
3f0d252442
commit
7cd935026e
2 changed files with 29 additions and 15 deletions
34
lib.nix
34
lib.nix
|
@ -3,10 +3,21 @@ let
|
|||
inherit (builtins) concatStringsSep filter mapAttrs attrValues;
|
||||
|
||||
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:
|
||||
if isLuaNil val then "nil"
|
||||
else if isDictItem val then toLuaDictItem val.name val.value
|
||||
else if isAttrs val then toLuaDict val
|
||||
else if isList val then toLuaList val
|
||||
else if isString val then toLuaStr val
|
||||
|
@ -18,29 +29,24 @@ let
|
|||
toLuaList = val:
|
||||
wrapObj (excludeNull (map toLua val));
|
||||
|
||||
toLuaDict = 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;
|
||||
toLuaDict = val: toLua (attrValues (mapAttrs mkDictItem val));
|
||||
|
||||
excludeNull = val: filter (v: !(isNull v)) val;
|
||||
|
||||
wrapObj = val: "{ ${concatStringsSep ", " val} }";
|
||||
|
||||
toLuaStr = val: "\"${val}\"";
|
||||
toLuaStr = val: "\"${validString val}\"";
|
||||
|
||||
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
|
||||
{
|
||||
inherit toLua;
|
||||
inherit mkLuaNil;
|
||||
inherit mkLuaNil mkDictItem;
|
||||
}
|
||||
|
|
10
lib.test.nix
10
lib.test.nix
|
@ -2,7 +2,7 @@
|
|||
|
||||
let
|
||||
nix2lua = import ./lib.nix;
|
||||
inherit (nix2lua) toLua mkLuaNil;
|
||||
inherit (nix2lua) toLua mkLuaNil mkDictItem;
|
||||
in
|
||||
pkgs.lib.runTests {
|
||||
"test returns null" = {
|
||||
|
@ -69,4 +69,12 @@ pkgs.lib.runTests {
|
|||
};
|
||||
expected = "{ [\"first\"] = { [\"second\"] = { [\"last\"] = \"hello\" } } }";
|
||||
};
|
||||
"test returns array with dict items" = {
|
||||
expr = toLua [
|
||||
"foo"
|
||||
(mkDictItem "foo" "hello")
|
||||
10
|
||||
];
|
||||
expected = "{ \"foo\", [\"foo\"] = \"hello\", 10 }";
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue