From a87f7718c6e42fa2edabe73a571d27badf9fc6c4 Mon Sep 17 00:00:00 2001 From: CodeFetch Date: Wed, 30 Dec 2020 05:08:27 +0100 Subject: [PATCH] packages: introduce toboolean function in gluon.util This commit introduces a simple function to convert standard values which are regularly being used as booleans like numbers and strings to booleans to mimic the behavior of other programming languages. --- .../luasrc/usr/lib/lua/gluon/util.lua | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/package/gluon-core/luasrc/usr/lib/lua/gluon/util.lua b/package/gluon-core/luasrc/usr/lib/lua/gluon/util.lua index a3c5456f..a1eacb9d 100644 --- a/package/gluon-core/luasrc/usr/lib/lua/gluon/util.lua +++ b/package/gluon-core/luasrc/usr/lib/lua/gluon/util.lua @@ -26,6 +26,30 @@ function M.trim(str) return (str:gsub("^%s*(.-)%s*$", "%1")) end +-- Allows the conversion to booleans of standard values which are regularly being used as +-- booleans like numbers (everything but 0 is true) and strings like "True" +function M.toboolean(val) + -- 'nil' and 'false' are false + if not val then return false end + + -- use the string representation + val = tostring(val) + + -- if it is literally 'true' in lowercase + if val:lower() == 'true' then + return true + end + + val = tonumber(val) + -- every number but 0 is true + if val and val ~= 0 then + return true + end + + -- everything else is false + return false +end + function M.contains(table, value) for k, v in pairs(table) do if value == v then