lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

I am pleased to announce the first stable release of `c3`, an
implementation in pure Lua of the C3 linearization algorithm.

This implementation extracts super classes with a user-defined function,
and handles cycles.


This module is available as a Lua rock:

    luarocks install c3


First, require this module and create an instance of the algorithm
using your own `superclass` function.

Here, we simply use the identity function for `superclass`: the
superclasses are stored within the class, from `1` (the lowest priority)
to `n` (the highest priority).

    C3 = require "c3"
    c3 = {
      superclass = function (x) return x end,

Then, build the class hierarchy. Here, we follow the example given in
[Wikipedia]( We check
that linearization works as expected:

    local o  = {}
    local a  = { o, }
    local b  = { o, }
    local c  = { o, }
    local d  = { o, }
    local e  = { o, }
    local k1 = { c, b, a, }
    local k2 = { e, b, d, }
    local k3 = { d, a, }
    local z  = { k3, k2, k1, }
    local assert = require "luassert"
    assert.are.same (c3 (o ), { o, })
    assert.are.same (c3 (a ), { o, a, })
    assert.are.same (c3 (b ), { o, b, })
    assert.are.same (c3 (c ), { o, c, })
    assert.are.same (c3 (d ), { o, d, })
    assert.are.same (c3 (e ), { o, e, })
    assert.are.same (c3 (k1), { o, c, b, a, k1, })
    assert.are.same (c3 (k2), { o, e, b, d, k2, })
    assert.are.same (c3 (k3), { o, a, d, k3, })
    assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, })

Notice that the `superclass` function takes as input a class, and
returns its direct superclasses, from the lowest to the highest priority.

The C3 function returns a linearization of the classes, also from
the lowest to the highest priority. These orders differ from the one
used in the [Wikipedia](
article, but they allow an efficient implementation.