Sophie

Sophie

distrib > Fedora > 16 > i386 > by-pkgid > 9a513bb0f515a28c4c982655dfd62387 > files > 8

lua-lgi-0.6.2-5.fc16.i686.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>LGI User's Guide</title>
	<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>

<h1>LGI User's Guide</h1>

<p>All LGI functionality is exported through <code>lgi</code> module.  To access it,
use standard <code>require</code> construct, e.g.:</p>

<pre><code>local lgi = require 'lgi'
</code></pre>

<p>Note that lgi does not use <code>module</code> function, so it does <em>not</em>
automatically insert itself into globals, the return value from
<code>require</code> call has to be used.</p>

<h2>1. Importing libraries</h2>

<p>To use any introspection-enabled library, it has to be imported first.
Simple way to import it is just referencing its name in <code>lgi</code>
namespace, like this:</p>

<pre><code>local GLib = lgi.GLib
local GObject = lgi.GObject
local Gtk = lgi.Gtk
</code></pre>

<p>This imports the latest version of the module which can be found.
When exact version is requested, use `lgi.require(modulename,
version)`:</p>

<pre><code>local Gst = lgi.require('Gst', '0.10')
</code></pre>

<h3>1.1. Repository structure</h3>

<p>Importing library creates table containing all elements which are
present in the library namespace - all classes, structures, global
functions, constants etc.  All those elements are directly accessible, e.g.</p>

<pre><code>assert(GLib.PRIORITY_DEFAULT == 0)
</code></pre>

<p>Note that all elements in the namespace are lazy-loaded to avoid
excessive memory overhead and initial loading time.  To force
eager-loading, all namespaces (and container elements in them, like
classes, structures, enums etc) contains <code>_resolve(deep)</code> method, which
loads all contents eagerly, possibly recursively if <code>deep</code> argument is
<code>true</code>.  So e.g.</p>

<pre><code>dump(Gtk.Widget:_resolve(true), 3)
</code></pre>

<p>prints everything available in Gtk.Widget class, and</p>

<pre><code>dump(Gio:_resolve(true), 5)
</code></pre>

<p>dumps the whole contents of Gio package.</p>

<p>Note: the <code>dump</code> function used in this manual is part of
<code>cli-debugger</code> Lua package.  Of course, you can use any kind of
table-dumping facility you are used to instead.</p>

<h2>2. Mapping of types between GLib and Lua</h2>

<p>In order to call methods and access properties and fields from Lua, a
mapping between GLib types and Lua types is established.</p>

<ul>
    <li><code>void</code> is ignored, does not produce any Lua value</li>
    <li><code>gboolean</code> is mapped to Lua's <code>boolean</code> type, with <code>true</code> and
    <code>false</code> values</li>
    <li>All numeric types are mapped to Lua's <code>number</code> type</li>
    <li>Enumerations are primarily handled as strings with uppercased GType
    nicks, optionally the direct numeric values are also accepted.</li>
    <li>Bitflags are primarily handled as lists or sets of strings with
    uppercased GType nicks, optionally the direct numeric values are
    also accepted.</li>
    <li><code>gchar*</code> string is mapped to Lua as <code>string</code> type, UTF-8 encoded</li>
    <li>C array types and <code>GArray</code> is mapped to Lua tables, using array part
    of the table.  Note that although in C the arrays are 0-based, when
    copied to Lua table, they are 1-based (as Lua uses 1-based arrays).</li>
    <li><code>GList</code> and <code>GSList</code> is also mapped to Lua array part of tables.</li>
    <li><code>GHashTable</code> is mapped to Lua table, fully utilizing key-value and
    GHashTable's key and value pairs.</li>
    <li>C arrays of 1-byte-sized elements (i.e. byte buffers) is mapped to
    Lua <code>string</code> instead of tables, although when going Lua->GLib
    direction, tables are also accepted for this type of arrays.</li>
    <li>GObject class, struct or union is mapped to LGI instances of
    specific class, struct or union.  It is also possible to pass <code>nil</code>,
    in which case the <code>NULL</code> is passed to C-side (but only if the
    annotation <code>(allow-none)</code> of the original C method allows passing
    <code>NULL</code>).</li>
    <li><code>gpointer</code> are mapped to Lua <code>lightuserdata</code> type.  In Lua->GLib
    direction, following values are accepted for <code>gpointer</code> type:
    <ul>
        <li>Lua <code>string</code> instances</li>
        <li>Instances of LGI classes, structs or unions</li>
        <li>Binary buffers (see below)</li>
    </ul></li>
</ul>

<h3>2.1. Modifiable binary buffers</h3>

<p>Pure Lua lacks native binary modifiable buffer structure, which is a
problem for some GObject APIs, for example <code>Gio.InputStream.read()</code>,
which request pre-allocated buffer which will be modified (filled)
during the call.  To overcome this problem, LGI adopts the
<a href="http://permalink.gmane.org/gmane.comp.lang.lua.general/79288
" title="Defining a library for mutable byte arrays">bytes proposal</a>.  Since the standalone
implementation of this proposal does not seem to be available yet, LGI
uses its own implementation which is used when no external <code>bytes</code>
package can be found.  An example of <code>bytes</code> buffer usage follows:</p>

<pre><code>local lgi = require 'lgi'
local bytes = require 'bytes'
local Gio = lgi.Gio

local stream = assert(Gio.File.new_for_path('foo.txt'):read())
local buffer = bytes.new(50)
local size = stream:read(buffer, #buffer)
assert(size &gt;= 0)
print(tostring(buffer):sub(1, size))
</code></pre>

<p>Note that not full <code>bytes</code> proposal is currently implemented, 'Derived
operations' are not available except creating buffer from string using
<code>bytes.new</code> function.</p>

<h3>2.2. Calling functions and methods</h3>

<p>When calling GLib functions, following conventions apply:</p>

<ul>
    <li>All input arguments are mapped to Lua inputs</li>
    <li>Return value is the first Lua return value</li>
    <li>All output arguments follow the return value</li>
    <li>In/Out arguments are both accepted as input and are also added into
    Lua returns.</li>
    <li>Functions reporting errors through <code>GError **</code> as last argument use
    Lua standard error reporting - they typically return boolean value
    indicating either success or failure, and if failure occurs,
    following return values represent error message and error code.</li>
</ul>

<h4>2.2.1. Phantom boolean return values</h4>

<p>GLib based libraries often use boolean return value indicating whether
logically-output argument is filled in or not.  Typical example is
`gboolean gtk<em>tree</em>model<em>get</em>iter<em>first(GtkTreeModel *tree</em>model,
GtkTreeIter *iter)<code>, where</code>iter` is filled in case of success, and
untouched in case of failure.  Normal binding of such function feels a
bit unnatural in Lua:</p>

<pre><code>local ok, iter = model:get_iter_first()
-- Even in case of failure, iter contains new 0-initialized
-- instance of the iterator, so following line is necessary:
if not ok then iter = nil end
</code></pre>

<p>To ease usage of such method, LGI avoids returning first boolean
return.  If C function returns <code>false</code> in this case, all other output
arguments are returned as <code>nil</code>.  This means that previous example
should be instead written simply as:</p>

<pre><code>local iter = model:get_iter_first()
</code></pre>

<h3>2.3. Callbacks</h3>

<p>When some GLib function or method requires callback argument, a Lua
function should be provided (or userdata or table implementing
<code>__call</code> metamethod), and position for callback context (usually
called <code>user_data</code> in GLib function signature) should be ignored
completely.  Callbacks are invoked in the context of Lua coroutine
which invoked the original call, unless the coroutine is suspended -
in this, case a new coroutine is automatically created and callback is
invoked in this new context.</p>

<p>Callback arguments and return values are governed by the same rules of
argument and type conversions as written above.  If the Lua callback
throws an error, the error is <em>not</em> caught by the calling site,
instead propagated out (usually terminating unless there is some
<code>pcall</code> in the call chain).</p>

<p>It is also possible to provide coroutine instance as callback
argument.  In this case, the coroutine is resumed, providing callback
arguments as parameters to resume (therefore they are return values of
<code>coroutine.yield()</code> call which suspended the coroutine passed as
callback argument).  The callback is in this case considered to return
when either coroutine terminates (in this case, callback return
value(s) are coroutine final result(s)) or yields again (in this case,
callback return value(s) are arguments to <code>coroutine.yield()</code> call).
This mode of operation is very useful when using Gio-style
asynchronous calls; see <code>samples\giostream.lua</code> for example usage of
this technique.</p>

<h2>3. Classes</h2>

<p>Classes are usually derived from <code>GObject</code> base class.  Classes
contain entities like properties, methods and signals and provide
inheritance, i.e. entities of ancestor class are also available in all
inherited classes.  LGI supports Lua-like access to entities using <code>.</code>
and <code>:</code> operators.</p>

<p>There is no need to invoke any memory management GObject controls,
like <code>ref</code> or <code>unref</code> methods, because LGI handles reference
management transparently underneath.  In fact, calling these low-level
methods can probably always be considered either as a bug or
workaround for possible bug in LGI :-)</p>

<h3>3.1. Creating instances</h3>

<p>To create new instance of the class (i.e. new object), call class
declaration as if it is a method:</p>

<pre><code>local window = Gtk.Window()
</code></pre>

<p>Optionally, it is possible to pass single argument, table containing
entity name mapping to entity value.  This way it is possible to
initialize properties, fields and even signal handlers in the class
construction:</p>

<pre><code>local window = Gtk.Window {
   title = "Title",
   on_destroy = function() print("Destroyed") end
}
</code></pre>

<p>For some classes, which behave like containers of other things, lgi
allows adding also a list of children into the array part of the
argument table, which contains children element to be added.  A
typical example is <code>Gtk.Container</code>, which allows adding element in the
constructor table, allowing construction of the whole widget
hierarchy in Lua-friendly way:</p>

<pre><code>local window = Gtk.Window {
   title = "Title",
   on_destroy = function() print("Destroyed") end,
   Gtk.Grid {
      Gtk.Label { label = "Contents", expand = true },
      Gtk.Statusbar {}
   }
}
</code></pre>

<p>There is also possibility to create instances of classes for which the
introspection typelib data is not available, only GType is known.  Use
<code>GObject.Object.new()</code> as illustrated in following sample:</p>

<pre><code>local gtype = 'ForeignWidget'
local widget = GObject.Object.new(gtype)
local window = Gtk.Window { title = 'foreign', widget }
</code></pre>

<h3>3.2. Calling methods</h3>

<p>Methods are functions grouped inside class (or interface)
declarations, accepting pointer to class instance as first argument.
Most usual technique to invoke method is using <code>:</code> operator,
e.g. <code>window:show_all()</code>.  This is of course identical with
<code>window.show_all(window)</code>, as is convention in plain Lua.</p>

<p>Method declaration itself is also available in the class and it is
possible to invoke it without object notation, so previous example can
be also rewritten as <code>Gtk.Window.show_all(window)</code>.  Note that this
way of invoking removes dynamic lookup of the method from the object
instance type, so it might be marginally faster.  However, in case
that <code>window</code> is actually instance of some <code>GtkWindow</code> descendant,
lets say <code>MyWindow</code>, which also defined <code>my_window_show_all()</code> method,
there will be a difference: <code>window:show_all()</code> will invoke
<code>my_window_show_all(window)</code>, while <code>Gtk.Window.show_all(window)</code> will
of course invoke non-specialized <code>gtk_widget_show_all(window)</code>.</p>

<h4>3.2.1. Static methods</h4>

<p>Static methods (i.e. functions which do not take class instance as
first argument) are usually invoked using class namespace,
e.g. <code>Gtk.Window.list_toplevels()</code>.  Very common form of static
methods are <code>new</code> constructors, e.g. <code>Gtk.Window.new()</code>.  Note that in
most cases, <code>new</code> constructors are provided only as convenience for C
programmers, in LGI it might be preferable to use `window =
Gtk.Window { type = Gtk.WindowType.TOPLEVEL }<code>instead of</code>window =
Gtk.Window.new(Gtk.WindowType.TOPLEVEL)`.</p>

<h3>3.3. Accessing properties</h3>

<p>Object properties are accessed simply by using <code>.</code> operator.
Continuing previous example, we can write `window.title = window.title
.. ' - new'`.  Note that in GObject system, property and signal names
can contain <code>-</code> character.  Since this character is illegal in Lua
identifiers, it is mapped to <code>_</code>, so <code>can-focus</code> window property is
accessed as <code>window.can_focus</code>.</p>

<h3>3.4. Connecting signals</h3>

<p>Signals are exposed as <code>on_signalname</code> entities on the class
instances.  Assigning Lua function connects that function to the
signal.  Signal routine gets object as first argument, followed by
other arguments of the signal. Simple example:</p>

<pre><code>local window = Gtk.Window()
window.on_destroy = function(w)
   assert(w == window)
   print("Destroyed", w)
end
</code></pre>

<p>Note that because of Lua's syntactic sugar for object access and
function definition, it is possible to use signal connection even in
following way:</p>

<pre><code>local window = Gtk.Window()
function window:on_destroy()
   assert(self == window)
   print("Destroyed", self)
end
</code></pre>

<p>Reading signal entity provides temporary table which can be used for
connecting signal with specification of the signal detail (see GObject
documentation on signal detail explanation).  An example of handler
which is notified whenever window is activated or deactivated follows:</p>

<pre><code>local window = Gtk.Window()
window.on_notify['is-active'] = function(self, pspec)
   assert(self == window)
   assert(pspec.name == 'is-active')
   print("Window is active:", self.is_active)
end
</code></pre>

<p>Both forms of signal connection connect handler before default signal
handler.  If connection after default signal handler is wanted (see
<code>G_CONNECT_AFTER</code> documentation for details), the most generic
connection call has to be used: `object.on_signalname:connect(target,
detail, after)`.  Previous example rewritten using this connection
style follows:</p>

<pre><code>local window = Gtk.Window()
local function notify_handler(self, pspec)
   assert(self == window)
   assert(pspec.name == 'is-active')
   print("Window is active:", self.is_active)
end
window.on_notify:connect(notify_handler, 'is-active', false)
</code></pre>

<h3>3.5. Dynamic typing of classes</h3>

<p>LGI assigns real class types to class instances dynamically, using
runtime GObject introspection facilities.  When new classes instance
is passed from C code into Lua, LGI queries the real type of the
object, finds the nearest type in the loaded repository and assigns
this type to the Lua-side created proxy for the object.  This means
that there is no casting needed in LGI (and there is also no casting
facility available).</p>

<p>Hopefully everything can be explained in following example.  Assume
that <code>demo.ui</code> is GtkBuilder file containing definition of <code>GtkWindow</code>
labeled <code>window1</code> and <code>GtkAction</code> called <code>action1</code> (among others).</p>

<pre><code>local builder = Gtk.Builder()
builder:add_from_file('demo.ui')
local window = builder:get_object('window1')
-- Call Gtk.Window-specific method
window:iconify()
local action = builder:get_object('action1')
-- Set Gtk.Action-specific property
action.sensitive = false
</code></pre>

<p>Although <code>Gtk.Builder.get_object()</code> method is marked as returning
<code>GObject*</code>, LGI actually checks the real type of returned object and
assigns proper type to it, so <code>builder:get_object('window1')</code> returns
instance of <code>Gtk.Window</code> and <code>builder:get_object('action1')</code> returns
instance of <code>Gtk.Action</code>.</p>

<p>Another mechanism which allows complete lack of casting in LGI is
automatic interface discovery.  If some class implements some
interface, the properties and methods of the interface are directly
available on the class instance.</p>

<h3>3.6. Accessing object's class instance</h3>

<p>GObject has the notion of object class.  There are sometimes useful
methods defined on objects class, which are accessible to LGI using
object instance pseudo-property <code>class</code>.  For example, to list all
properties registered for object's class, GObject library provides
<code>g_object_class_list_properties()</code> function.  Following sample
lists all properties registered for the given object
instance.</p>

<pre><code>function dump_props(obj)
   print("Dumping properties of ", obj)
   for _, pspec in pairs(obj.class:list_properties()) do
  print(pspec.name, pspec.value_type)
   end
end
</code></pre>

<p>Running <code>dump_props(Gtk.Window())</code> yields following output:</p>

<pre><code>Dumping props of    lgi.obj 0xe5c070:Gtk.Window(GtkWindow)
name    gchararray
parent  GtkContainer
width-request   gint
height-request  gint
visible gboolean
sensitive   gboolean
... (and so on)
</code></pre>

<h3>3.7. Querying the type of the object instances</h3>

<p>To query whether given Lua value is actually an instance of specified
class or subclass, class types define <code>is_type_of</code> method.  This
class-method takes one argument and checks, whether given argument as an
instance of specified class (or implements specified interface, when
called on interface instances).  Following examples demonstrate usage of
this construct:</p>

<pre><code>local window = Gtk.Window()
print(Gtk.Window:is_type_of(window))    -- prints 'true'
print(Gtk.Widget:is_type_of(window))    -- prints 'true'
print(Gtk.Buildable:is_type_of(window)) -- prints 'true'
print(Gtk.Action:is_type_of(window))    -- prints 'false'
print(Gtk.Window:is_type_of('string'))  -- prints 'false'
print(Gtk.Window:is_type_of('string'))  -- prints 'false'
print(Gtk.Window:is_type_of(nil))       -- prints 'false'
</code></pre>

<p>There is also possibility to query the type-table from instantiated
object, using <code>_type</code> property.</p>

<pre><code>-- Checks, whether 'unknown' conforms to the type of the 'template'
-- object.
function same_type(template, unknown)
   local type = template._type
   return type:is_type_of(unknown)
end
</code></pre>

<h2>4. Structures and unions</h2>

<p>Structures and unions are supported in a very similar way to classes.
They have only access to methods (in the same way as classes) and
fields, which are very similar to the representation of properties on
the classes.</p>

<h3>4.1. Creating instances</h3>

<p>Structure instances are created by 'calling' structure definition,
similar to creating new class: <code>local color = Gdk.RGBA()</code>.  For
simplest structures without constructor methods, the new structure is
allocated and zero-initialized.  It is also possible to pass table
containing fields and values to which the fields should be
initialized: <code>local blue = Gdk.RGBA { blue = 1, alpha = 1 }</code>.</p>

<p>If the structure has defined any constructor named <code>new</code>, it is
automatically mapped by LGI to the structure creation construct, so
calling <code>local main_loop = GLib.MainLoop(nil, false)</code> is exactly
equivalent with <code>local main_loop = GLib.MainLoop.new(nil, false)</code>, and
<code>local color = Clutter.Color(0, 0, 0, 255)</code> is exactly equivalent with
<code>local color = Clutter.Color.new(0, 0, 0, 255)</code>.</p>

<h3>4.2. Calling methods and accessing fields.</h3>

<p>Structure methods are called in the same way as class methods:
<code>struct:method()</code>, or <code>StructType.method()</code>.  For example:</p>

<pre><code>local loop = GLib.MainLoop(nil, false)
loop:run()
-- Following line is equivalent
GLib.MainLoop.run(loop)
</code></pre>

<p>Fields are accessed using <code>.</code> operator on structure instance, for example</p>

<pre><code>local color = Gdk.RGBA { alpha = 1 }
color.green = 0.5
print(color.red, color.green, color.alpha)
-- Prints: 0    0.5    1
</code></pre>

<h2>5. Enums and bitflags, constants</h2>

<p>LGI primarily maps enumerations to strings containing uppercased nicks
of enumeration constant names.  Optionally, a direct enumeration value
is also accepted.  Similarly, bitflags are primarily handled as sets
containing uppercased flag nicks, but also lists of these nicks or
direct numeric value is accepted.  When a numeric value cannot be
mapped cleanly to the known set of bitflags, the remaining number is
stored in the first array slot of the returned set.</p>

<p>Note that this behavior changed in lgi 0.4; up to that alpha release,
lgi handled enums and bitmaps exclusively as numbers only.  The change
is compatible in Lua->C direction, where numbers still can be used,
but incompatible in C->Lua direction, where lgi used to return
numbers, while now it returns either string with enum value or table
with flags.</p>

<h3>5.1. Accessing numeric values</h3>

<p>In order to retrieve real enum values from symbolic names, enum and
bitflags are loaded into repository as tables mapping symbolic names
to numeric constants.  Fro example, dumping <code>Gtk.WindowType</code> enum
yields following output:</p>

<blockquote>
    <p>dump(Gtk.WindowType)</p>
</blockquote>

<pre><code>["table: 0xef9bc0"] = {  -- table: 0xef9bc0
  TOPLEVEL = 0;
  POPUP = 1;
};
</code></pre>

<p>so constants can be referenced using <code>Gtk.WindowType.TOPLEVEL</code>
construct, or directly using string <code>'TOPLEVEL'</code> when a
<code>Gtk.WindowType</code> is expected.</p>

<h3>5.2. Backward mapping, getting names from numeric values</h3>

<p>There is another facility in LGI, which allows backward mapping of
numeric constants to symbolic names.  Indexing enum table with number
actually provides symbolic name to which the specified constant maps:</p>

<blockquote>
    <p>print(Gtk.WindowType[0])</p>
</blockquote>

<pre><code>TOPLEVEL
</code></pre>

<blockquote>
    <p>print(Gtk.WindowType[2])</p>
</blockquote>

<pre><code>nil
</code></pre>

<p>Indexing bitflags table with number provides table containing list of
all symbolic names which make up the requested value:</p>

<blockquote>
    <p>dump(Gtk.RegionFlags)</p>
</blockquote>

<pre><code>["table: 0xe5dd10"] = {  -- table: 0xe5dd10
  ODD = 2;
  EVEN = 1;
  SORTED = 32;
  FIRST = 4;
  LAST = 8;
</code></pre>

<blockquote>
    <p>dump(Gtk.RegionFlags[34])</p>
</blockquote>

<pre><code>["table: 0xedbba0"] = {  -- table: 0xedbba0
  SORTED = 32;
  ODD = 2;
};
</code></pre>

<p>This way, it is possible to check for presence of specified flag very
easily:</p>

<pre><code>if Gtk.RegionFlags[flags].ODD then
   -- Code handling region-odd case
endif
</code></pre>

<p>If the value cannot be cleanly decomposed to known flags, remaining
bits are accumulated into number stored at index 1:</p>

<blockquote>
    <p>dump(Gtk.RegionFlags[51])</p>
</blockquote>

<pre><code>["table: 0x242fb20"] = {  -- table: 0x242fb20
  EVEN = 1;
  SORTED = 32;
  [1] = 16;
  ODD = 2;
};
</code></pre>

<p>To construct numeric value which can be passed to a function expecting
an enum, it is possible to simply add requested flags.  However, there
is a danger if some definition contains multiple flags , in which case
numeric adding produces incorrect results.  Therefore, it is possible
to use bitflags pseudoconstructor', which accepts table containing
requested flags:</p>

<blockquote>
    <p>=Gtk.RegionFlags { 'FIRST', 'SORTED' }</p>
</blockquote>

<pre><code>36
</code></pre>

<blockquote>
    <p>=Gtk.RegionFlags { Gtk.RegionFlags.ODD, 16, 'EVEN' }</p>
</blockquote>

<pre><code>19
</code></pre>

<h2>6. Threading and synchronization</h2>

<p>Lua platform does not allow running real concurrent threads in single
Lua state.  This rules out any usage of GLib's threading API.
However, wrapped libraries can be using threads, and this can lead to
situations that callbacks or signals can be invoked from different
threads.  To avoid corruption which would result from running multiple
threads in a single Lua state, LGI implements one internal lock
(mutex) which protects access to Lua state.  LGI automatically locks
(i.e. waits on) this lock when performing C->Lua transition (invoking
Lua callback or returning from C call) and unlocks it on Lua->C
transition (returning from Lua callback or invoking C call).</p>

<p>In a typical GLib-based application, most of the runtime is spent
inside mainloop.  During this time, LGI lock is unlocked and mainloop
can invoke Lua callbacks and signals as needed.  This means that
LGI-based application does not have to worry about synchronization at
all.</p>

<p>The only situation which needs intervention is when mainloop is not
used or a different form of mainloop is used (e.g. Copas scheduler, Qt
UI etc).  In this case, LGI lock is locked almost all the time and
callbacks and signals are blocked and cannot be delivered.  To cope
with this situation, a <code>lgi.yield()</code> call exists.  This call
temporarily unlocks the LGI lock, letting other threads to deliver
waiting callbacks, and before returning the lock is closed back.  This
allows code which runs foreign, non-GLib style of mainloop to stick
<code>lgi.yield()</code> calls to some repeatedly invoked place and thus allowing
delivery of callbacks from other threads.</p>

<h2>7. Logging</h2>

<p>GLib provides generic logging facility using <code>g_message</code> and similar C
macros.  These utilities are not directly usable in Lua, so LGI
provides layer which allows logging messages using GLib logging
facilities and controlling behavior of logging methods.</p>

<p>All logging is controlled by <code>lgi.log</code> table.  To allow logging in
LGI-enabled code, <code>lgi.log.domain(name)</code> method exists.  This method
returns table containing methods <code>message</code>, <code>warning</code>, <code>critical</code>,
<code>error</code> and <code>debug</code> methods, which take format string optionally
followed by inserts and logs specified string.  An example of typical
usage follows:</p>

<pre><code>local lgi = require 'lgi'
local log = lgi.log.domain('myapp')

-- This is equivalent of C 'g_message("A message %d", 1)'
log.message("A message %d", 1)

-- This is equivalent to C 'g_warning("Not found")'
log.warning("Not found")
</code></pre>

<p>Note that format string is formatted using Lua's <code>string.format()</code>, so
the rules for Lua formatting strings apply here.</p>

<h2>8. Interoperability with native code</h2>

<p>There might be some scenarios where it is important to either export
objects or records created in Lua into C code or vice versa.  LGI
allows transfers using Lua <code>lightuserdata</code> type.  To get native
pointer to the LGI object, use <code>_native</code> attribute of the object.  To
create LGI object from external pointer, it is possible to pass
lightuserdata with object pointer to type constructor.  Following
example illustrates both techniques:</p>

<pre><code>-- Create Lua-side window object.
local window = Gtk.Window { title = 'Hello' }

-- Get native pointer to this object.
local window_ptr = window._native

// window_ptr can be now passed to C code, which can use it.
GtkWindow *window = lua_touserdata (L, x);
char *title;
g_object_get (window, "title", &amp;title);
g_assert (g_str_equal (title, "Hello"));
g_free (title);

// Create object on the C side and pass it to Lua
GtkButton *button = gtk_button_new_with_label ("Foreign");
lua_pushlightuserdata (L, button);
lua_call (L, ...);

-- Retrieve button on the Lua side.
assert(type(button) == 'userdata')
window:add(Gtk.Button(button))
</code></pre>

<p>Note that while the example demonstrates objects, the same mechanism
works also for structures and unions.</p>

<h2>9. GObject basic constructs</h2>

<p>Although GObject library is already covered by gobject-introspection,
most of the elements in it are basic object system building blocks and
either need or greatly benefit from special handling by LGI.</p>

<h3>9.1. GObject.Type</h3>

<p>Contrary to C <code>GType</code> representation (which is unsigned number), LGI
represents GType by its name, as a string.  GType-related constants
and methods useful for handling GType are present in <code>GObject.Type</code>
namespace.</p>

<p>Fundamental GType names are imported as constants into GObject.Type
namespace, so that it is possible to use for example
<code>GObject.Type.INT</code> where <code>G_TYPE_INT</code> would be used in C code.
Following constants are available:</p>

<blockquote>
    <p><code>NONE</code>, <code>INTERFACE</code>, <code>CHAR</code>, <code>UCHAR</code>, <code>BOOLEAN</code>,
    <code>INT</code>, <code>UINT</code>, <code>LONG</code>, <code>ULONG</code>, <code>INT64</code>, <code>UINT64</code>,
    <code>ENUM</code>, <code>FLAGS</code>, <code>FLOAT</code>, <code>DOUBLE</code>, <code>STRING</code>,
    <code>POINTER</code>, <code>BOXED</code>, <code>PARAM</code>, <code>OBJECT</code>, <code>VARIANT</code></p>
</blockquote>

<p>Moreover, functions operating on <code>GType</code> are also present in
<code>GObject.Type</code> namespace:</p>

<blockquote>
    <p><code>parent</code>, <code>depth</code>, <code>next_base</code>, <code>is_a</code>, <code>children</code>, <code>interfaces</code>,
    <code>query</code>, <code>fundamental_next</code>, <code>fundamental</code></p>
</blockquote>

<p>When transferring <code>GType</code> value from Lua to C (e.g. calling function
which accepts argument of <code>GType</code>), it is possible to use either
string with type name, number representing numeric <code>GType</code> value, or
any loaded component which has its type assigned.  Some examples of
<code>GType</code> usage follow:</p>

<pre><code>lgi = require 'lgi'
GObject = lgi.GObject
Gtk = lgi.Gtk

print(GObject.Type.NONE)
print(GObject.Type.name(GObject.Type.NONE))
-- prints "void" in both cases

print(GObject.Type.name(Gtk.Window))
-- prints "GtkWindow"

print(GObject.Type.is_a(Gtk.Window, GObject.Type.OBJECT))
-- prints "true"

print(GObject.Type.parent(Gtk.Window))
-- prints "GtkBin"
</code></pre>

<h3>9.2. GObject.Value</h3>

<p>LGI does not implement any automatic <code>GValue</code> boxing or unboxing,
because this would involve guessing <code>GType</code> from Lua value, which is
generally unsafe.  Instead, an easy to use and convenient wrappers for
accessing <code>GValue</code> type and contents are provided.</p>

<h4>9.2.1. Creation</h4>

<p>To create new <code>GObject.Value</code> instances, use similar method as for
creating new structures or classes, i.e. 'call' <code>GObject.Value</code> type.
The call has two optional arguments, specifying <code>GType</code> of newly
created <code>GValue</code> and optionally also the contents of the value.  A few
examples for creating new values follow:</p>

<pre><code>local lgi = require 'lgi'
local GObject = lgi.GObject
local Gtk = lgi.Gtk

local empty = GObject.Value()
local answer = GObject.Value(GObject.Type.INT, 42)
local null_window = GObject.Value(Gtk.Window)
local window = GObject.Value(Gtk.Window, Gtk.Window())
</code></pre>

<h4>9.2.2. Boxing and unboxing GObject.Value instances</h4>

<p><code>GObject.Value</code> adds two new virtual properties, called <code>gtype</code> and
<code>value</code>.  <code>gtype</code> contains actual type of the value, while <code>value</code>
provides access to the contents of the value.  Both properties are
read/write.  Reading of them queries current <code>GObject.Value</code> state,
i.e. reading <code>value</code> performs actual <code>GValue</code> unboxing.  Writing
<code>value</code> performs value boxing, i.e. the source Lua item is attempted
to be stored into the <code>GObject.Value</code>.  Writing <code>gtype</code> attempts to
change the type of the value, and in case that value already has a
contents, it also converts contents to the new type (using
<code>g_value_transform()</code>).  Examples here continue using the values
created in previous section example:</p>

<pre><code>assert(empty.gtype == nil)
assert(empty.value == nil)
assert(answer.gtype == GObject.Type.INT)
assert(answer.value == 42)
assert(null_window.gtype == 'GtkWindow')
assert(null_window.value == nil)

empty.gtype = answer.gtype
empty.value = 1
assert(empty.gtype == GObject.Type.INT)
assert(empty.value == 1)
answer.gtype = GObject.Type.STRING)
assert(answer.value == '42')
</code></pre>

<p>Although <code>GObject.Value</code> provides most of the GValue documented
methods (e.g. <code>g_value_get_string()</code> is accessible as
<code>GObject.Value.get_string()</code> and getting string contents of the value
instance can be written as <code>value:get_string()</code>), <code>value</code> and <code>gtype</code>
abstract properties are recommended to be used instead.</p>

<h3>9.3. GObject.Closure</h3>

<p>Similar to GObject.Value, no automatic GClosure boxing is implemented.
To create a new instance of <code>GClosure</code>, 'call' closure type and
provide Lua function as an argument:</p>

<pre><code>closure = GObject.Closure(func)
</code></pre>

<p>When the closure is emitted, a Lua function is called, getting
<code>GObject.Value</code> as arguments and expecting to return <code>GObject.Value</code>
instance.</p>

</body></html>