From f9f06de79e87f64a839bc01cb2d80201b53e3047 Mon Sep 17 00:00:00 2001 From: Thijs Schreijer Date: Mon, 7 Jan 2019 15:36:30 +0100 Subject: [PATCH] fix(map) setdefault will now honor a 'false' value --- lua/pl/Map.lua | 15 +++++++++++---- tests/test-map.lua | 3 +++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lua/pl/Map.lua b/lua/pl/Map.lua index 2624dc81..572b22ad 100644 --- a/lua/pl/Map.lua +++ b/lua/pl/Map.lua @@ -55,10 +55,17 @@ function Map:items() return ls end ---- Will return the existing value, or if it doesn't exist it will set --- a default value and return it. -function Map:setdefault(key, defaultval) - return self[key] or self:set(key,defaultval) or defaultval +--- set a value in the map if it doesn't exist yet. +-- @param key the key +-- @param default value to set +-- @return the value stored in the map (existing value, or the new value) +function Map:setdefault(key, default) + local val = self[key] + if val ~= nil then + return val + end + self:set(key,default) + return default end --- size of map. diff --git a/tests/test-map.lua b/tests/test-map.lua index 93e511a3..1c0bee61 100644 --- a/tests/test-map.lua +++ b/tests/test-map.lua @@ -78,6 +78,9 @@ asserteq( {'gamma', 3}, } ) +v = m:set("alpha", false) +v = m:setdefault("alpha", true) -- falsy value should not be altered +asserteq(false, m:get("alpha"))