Skip to content

Commit

Permalink
Merge pull request #40 from iwanders/fix-losing-values-on-mixed-key-t…
Browse files Browse the repository at this point in the history
…ables

Prevent losing entries with mixed key tables
  • Loading branch information
gvvaughan committed Nov 27, 2020
2 parents 96832dd + eb37e45 commit 0011bc5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/lyaml/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,24 @@ local dumper_mt = {
elseif itsa == 'string' or itsa == 'boolean' or itsa == 'number' then
return self:dump_scalar(node)
elseif itsa == 'table' then
if #node > 0 then
-- Something is only a sequence if its keys start at 1
-- and are consecutive integers without any jumps.
local prior_key = 0
local is_pure_sequence = true
local i, v = next(node, nil)
while i and is_pure_sequence do
if type(i) ~= "number" or (prior_key + 1 ~= i) then
is_pure_sequence = false -- breaks the loop
else
prior_key = i
i, v = next(node, prior_key)
end
end
if is_pure_sequence then
-- Only sequentially numbered integer keys starting from 1.
return self:dump_sequence(node)
else
-- Table contains non sequential integer keys or mixed keys.
return self:dump_mapping(node)
end
else -- unsupported Lua type
Expand Down
15 changes: 15 additions & 0 deletions spec/lib_lyaml_spec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@ specify lyaml:
- it writes a mapping: |
expect (lyaml.dump {{a=1, b=2, c=3, d=""}}).
to_contain.all_of {"a: 1", "b: 2", "c: 3", "d: ''"}
- it writes a mapping of mixed keys: |
expect (lyaml.dump {{[1]=1, [2]=2, three="three", four="4", [5]="five"}}).
to_contain.all_of {"1: 1", "2: 2", "three: three", "four: '4'", "5: five"}
- it writes a mapping of integer keys starting at two: |
expect (lyaml.dump {{[2]=2, [3]=3, [4]=4}}).
to_contain.all_of {"2: 2", "3: 3", "4: 4"}
- it writes a mapping of mixed keys starting at one: |
expect (lyaml.dump {{[1]=1, [2]=2, [3]=3, foo="bar"}}).
to_contain.all_of {"1: 1", "2: 2", "3: 3", "foo: bar"}
- it writes a mapping of mixed keys starting at two: |
expect (lyaml.dump {{[2]=2, [3]=3, [4]=4, foo="bar"}}).
to_contain.all_of {"2: 2", "3: 3", "4: 4", "foo: bar"}
- it writes a table containing nils (jumps in index) as mapping: |
expect (lyaml.dump {{1, 2, nil, 3, 4}}).
to_contain.all_of {"1: 1", "2: 2", "4: 3", "5: 4"}
- context anchors and aliases:
- before:
Expand Down

0 comments on commit 0011bc5

Please sign in to comment.