From 7e8f3e9b9b64fffc33debcabf919673d0bc6c96c Mon Sep 17 00:00:00 2001 From: Emmanuel Lepage Vallee Date: Mon, 7 Aug 2017 17:04:36 -0400 Subject: [PATCH] widget: Add a flexible generic constructor This avoid copy pasting this kind of code in many places. --- lib/wibox/widget/base.lua | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/wibox/widget/base.lua b/lib/wibox/widget/base.lua index 6e21e735..168d0d53 100644 --- a/lib/wibox/widget/base.lua +++ b/lib/wibox/widget/base.lua @@ -584,6 +584,34 @@ function base.make_widget_declarative(args) return setmetatable(w, mt) end +--- Create a widget from an undetermined value. +-- +-- The value can be: +-- +-- * A widget (in which case nothing new is created) +-- * A declarative construct +-- * A constructor function +-- * A metaobject +-- +-- @param wdg The value. +-- @param[opt=nil] ... Arguments passed to the contructor (if any). +-- @treturn The new widget. +function base.make_widget_from_value(wdg, ...) + local is_table = type(wdg) == "table" + local is_function = ((not is_table) and type(wdg) == "function") + or (is_table and getmetatable(wdg) and getmetatable(wdg).__call) + + if is_function then + wdg = wdg(...) + elseif is_table and not wdg.is_widget then + wdg = base.make_widget_declarative(wdg) + else + assert(wdg.is_widget, "The argument is not a function, table, or widget.") + end + + return wdg +end + --- Create an empty widget skeleton. -- -- See [Creating new widgets](../documentation/04-new-widget.md.html).