Skip to content
Marco Aurélio da Silva edited this page Aug 30, 2017 · 1 revision
  • How to persist anonymous talents if talents are weak references for their decorated objects (that is, the talents definitions are easily discarded if the talent itself is not referenced anymore and thus collected)?

We could store them (the talent reference) on the target object itself during the decoration of objects (that is, talent acquisition). For example, the following talent dynamically created is stored on the object itself to prevent garbage collection of the applied talent (that is, preventing the releasing of the talent):

local function weapon (name, strength, accuracy)
    local talents = require 'talents'

    local talent = talents.talent {
        accuracy = talents.required ( ),
        strength = talents.required ( ),

        critical = function (self)
            if accuracy > strength then
                return 1 - (strength / accuracy)

            elseif accuracy == strength then
                return 0.70

            else
                return accuracy / strength
            end
        end,
    }

    local structure = {
        name     = name,
        accuracy = accuracy,
        strength = strength,
    }

    local weapon = talents.decorate (talent, structure)

    weapon.talent = talent

    return weapon
end

Later, such talent could be retrieved with talents.abstract or just by indexing the field talent. Note that such approach shouldn't be abused, it can introduce some memory/space leaks, this is the why of storing the talent on the result decorated object rather than the target one (the target object will live so long as the result object lives, only if the target itself is not referenced anymore by other party). It means that if you want to release/discard that talent, ensure that it's linear (that is, it is exclusive/unique referenced) and replace the associated selector with nil to discard such talent reference.

Clone this wiki locally