From dc43d7ceda246e634547cbb2227dd16c56b52a2b Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Wed, 24 Apr 2024 18:41:46 +0300 Subject: [PATCH] improve table keys --- lib.nix | 2 ++ lib.test.nix | 9 +++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib.nix b/lib.nix index 9f58a6c..14f25b5 100644 --- a/lib.nix +++ b/lib.nix @@ -184,8 +184,10 @@ let wrapObj = expr: "{ ${concatStringsSep ", " expr} }"; in wrapObj (excludeNull (map onValue expr)); + isValidFieldName = name: isString name && match "^[[:alpha:]_][[:alnum:]_]*$" name == [ ]; toLuaNamedField = name: expr: if isNull expr then null + else if isValidFieldName name then "${name} = ${expr}" else "[${toLuaString name}] = ${expr}"; toLuaTable = onValue: expr: onValue (attrValues (mapAttrs namedField expr)); diff --git a/lib.test.nix b/lib.test.nix index 7262265..34d1822 100644 --- a/lib.test.nix +++ b/lib.test.nix @@ -85,12 +85,13 @@ with nix2lua; pkgs.lib.runTests { float = 10.1; success = true; fail = false; + quoted-var = true; }; - expected = ''{ ["fail"] = false, ["float"] = 10.100000, ["foo"] = "hello", ["int"] = 10, ["success"] = true }''; + expected = ''{ fail = false, float = 10.100000, foo = "hello", int = 10, ["quoted-var"] = true, success = true }''; }; "test returns named table without nullable items" = { expr = toLua { foo = "hello"; bar = null; }; - expected = ''{ ["foo"] = "hello" }''; + expected = ''{ foo = "hello" }''; }; "test returns recursive named table" = { expr = toLua { @@ -100,7 +101,7 @@ with nix2lua; pkgs.lib.runTests { }; }; }; - expected = ''{ ["first"] = { ["second"] = { ["last"] = "hello" } } }''; + expected = ''{ first = { second = { last = "hello" } } }''; }; "test return recursive table" = { expr = toLua [ [ [ "foo" ] "bar" ] ]; @@ -112,7 +113,7 @@ with nix2lua; pkgs.lib.runTests { (namedField "foo" "hello") 10 ]; - expected = ''{ "foo", ["foo"] = "hello", 10 }''; + expected = ''{ "foo", foo = "hello", 10 }''; }; "test returns raw string" = { expr = toLua (raw "hello");