commit d0e5bf6: [Minor] Add a simple toboolean function

Vsevolod Stakhov vsevolod at highsecure.ru
Mon Aug 19 15:56:15 UTC 2019


Author: Vsevolod Stakhov
Date: 2019-08-19 16:21:20 +0100
URL: https://github.com/rspamd/rspamd/commit/d0e5bf6d4a1a134ae4978a27e4b6e6466601cab0

[Minor] Add a simple toboolean function

---
 lualib/lua_util.lua | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/lualib/lua_util.lua b/lualib/lua_util.lua
index 682a33bf5..363ce4a65 100644
--- a/lualib/lua_util.lua
+++ b/lualib/lua_util.lua
@@ -1171,4 +1171,39 @@ exports.table_digest = function(t)
  return h:base32()
 end
 
+---[[[
+-- @function lua_util.toboolean(v)
+-- Converts a string or a number to boolean
+-- @param {string|number} v
+-- @return {boolean} v converted to boolean
+--]]]
+exports.toboolean = function(v)
+  local true_t = {
+    ['1'] = true,
+    ['true'] = true,
+    ['TRUE'] = true,
+    ['True'] = true,
+  };
+  local false_t = {
+    ['0'] = false,
+    ['false'] = false,
+    ['FALSE'] = false,
+    ['False'] = false,
+  };
+
+  if type(v) == 'string' then
+    if true_t[v] == true then
+      return true;
+    elseif false_t[v] == false then
+      return false;
+    else
+      return false, string.format( 'cannot convert %q to boolean', v);
+    end
+  elseif type(v) == 'number' then
+    return (not (v == 0))
+  else
+    return false, string.format( 'cannot convert %q to boolean', v);
+  end
+end
+
 return exports


More information about the Commits mailing list