From d0e5bf6d4a1a134ae4978a27e4b6e6466601cab0 Mon Sep 17 00:00:00 2001 From: Vsevolod Stakhov Date: Mon, 19 Aug 2019 16:21:20 +0100 Subject: [PATCH] [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 -- 2.39.5