Skip to content

Instantly share code, notes, and snippets.

@Miqueas
Created January 28, 2021 03:42
Show Gist options
  • Save Miqueas/3eccc37d84c327eb1a25842c49ba48e7 to your computer and use it in GitHub Desktop.
Save Miqueas/3eccc37d84c327eb1a25842c49ba48e7 to your computer and use it in GitHub Desktop.
[Lua + GObject] Canonical GObject properties names
-- From my other Gist: https://gist.github.com/M1que4s/9f1eec873f87cb02238bd6de2d435705
local lgi = require("lgi")
local GObject = lgi.require("GObject", "2.0")
local Canonical = GObject.Object:derive("Canonical")
function Canonical:_class_init(Class)
function Class:set_property(id, val, pspec)
if id == 1 then self.priv["prop-a"] = val:get_string()
elseif id == 2 then self.priv["prop-b"] = val:get_string()
elseif id == 3 then self.priv["prop-c"] = val:get_string()
elseif id == 4 then self.priv["prop-d"] = val:get_string()
else GObject.OBJECT_WARN_INVALID_PROPERTY_ID(self, id, pspec) end
end
function Class:get_property(id, val, pspec)
if id == 1 then val:set_string(self.priv["prop-a"])
elseif id == 2 then val:set_string(self.priv["prop-b"])
elseif id == 3 then val:set_string(self.priv["prop-c"])
elseif id == 4 then val:set_string(self.priv["prop-d"])
else GObject.OBJECT_WARN_INVALID_PROPERTY_ID(self, id, pspec) end
end
Class:install_property(1,
GObject.ParamSpecString(
"prop-a", "Prop A", "Property A", "A",
{ GObject.ParamFlags.READWRITE, GObject.ParamFlags.CONSTRUCT }
)
)
Class:install_property(2,
GObject.ParamSpecString(
"prop-b", "Prop B", "Property B", "B",
{ GObject.ParamFlags.READWRITE, GObject.ParamFlags.CONSTRUCT }
)
)
Class:install_property(3,
GObject.ParamSpecString(
"prop-c", "Prop C", "Property C", "C",
{ GObject.ParamFlags.READWRITE, GObject.ParamFlags.CONSTRUCT }
)
)
Class:install_property(4,
GObject.ParamSpecString(
"prop-d", "Prop D", "Property D", "D",
{ GObject.ParamFlags.READWRITE, GObject.ParamFlags.CONSTRUCT }
)
)
end
--[[ Explanation:
In the C land, some GObject libraries have clases with properties
separated by dashes (-), but in other programming languages, that
isn't a valid name. So... GI (GObject Introspection) based bindings
(including Vala) commonly translates properties names like this:
From: example-property
To: example_property
Basically replace dashes (-) by underscores (_) and LGI also do
this in Lua. But... Lua allows use "strange" names in tables and
since object construction in LGI uses tables, we can use the
canonical properties names. So... Lets look how can do this:
]]
local o = Canonical({
["prop-a"] = "Prop a",
["prop-b"] = "Prop b",
["prop-c"] = "Prop c",
["prop-d"] = "Prop d"
})
-- And, that's it! We're using canonical names in all our code!
print(o["prop-a"])
print(o["prop-b"])
print(o["prop-c"])
print(o["prop-d"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment