From 81f3a8718071547f5fc82cab07178dd78502315b Mon Sep 17 00:00:00 2001 From: Starbeamrainbowlabs Date: Tue, 11 May 2021 22:12:04 +0100 Subject: [PATCH] wea.parse.chance: add weight mode --- worldeditadditions/utils/parse/chance.lua | 7 +++++-- worldeditadditions/utils/parse/weighted_nodes.lua | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/worldeditadditions/utils/parse/chance.lua b/worldeditadditions/utils/parse/chance.lua index 8126983..f8a9a7b 100644 --- a/worldeditadditions/utils/parse/chance.lua +++ b/worldeditadditions/utils/parse/chance.lua @@ -1,12 +1,15 @@ --- Parses a chance value, and returns the 1-in-N value thereof. --- @param str string The string to parse. +-- @param str string The string to parse. +-- @param invert_percent string The operation mode. Valid modes: "1-in-n" (default), "weight". "1-in-n" refers to a 1-in-N chance of something happening (lower numbers mean greater likelihood). "weight", on the other hand, is instead a weighting that something will happen (higher numbers mean a greater likelihood). -- @returns number|nil The 1-in-N chance if parsing was successful, otherwise nil. -function worldeditadditions.parse.chance(str) +function worldeditadditions.parse.chance(str, mode) + if not mode then mode = "1-in-n" end if tonumber(str) ~= nil then return tonumber(str) end if str:sub(#str) == "%" then local result = tonumber(str:sub(1, #str-1)) if not result then return nil end + if mode == "weight" then result = 100 - result end return 1 / (result / 100) -- Convert percentage to 1-in-N chance end return nil diff --git a/worldeditadditions/utils/parse/weighted_nodes.lua b/worldeditadditions/utils/parse/weighted_nodes.lua index ef5db74..cbabda3 100644 --- a/worldeditadditions/utils/parse/weighted_nodes.lua +++ b/worldeditadditions/utils/parse/weighted_nodes.lua @@ -27,7 +27,7 @@ function worldeditadditions.parse.weighted_nodes(parts, as_list, func_normalise) mode = MODE_EITHER elseif mode == MODE_EITHER then -- print("mode: either"); - local chance = tonumber(part) + local chance = worldeditadditions.parse.chance(part, "weight") if not chance then -- print("not a chance, trying a node name") local node_name @@ -59,5 +59,7 @@ function worldeditadditions.parse.weighted_nodes(parts, as_list, func_normalise) else result[last_node_name] = 1 end end + print(worldeditadditions.format.map(result, " ")) + return true, result end