Class Models for Lua

Unordered Array
loop.collection.UnorderedArray
Class of objects that store a sequence of values as a Lua array but removes the elements from any position without shifting the following elements. However it does not guarantee the order the values are stored in the array. This class is useful for storing efficiently a sequence of values that may be iterated in any order and the number of elements varies constantly during interation.
Behaves like an ordinary Lua array but provides an operation that removes an element at given position by replacing it with the last element of the array and then frees the last position.
Behavior
Methods
add(value)
- Adds value
value
to the end of the array. Equivalent toself[#self + 1] = element
. remove(index)
- Replaces the element at position
index
with the last element of the array and frees the last position. Ifindex
is out of the array bounds then the call has no effect.
Examples
Scheduler of independent threads (i.e., does not interact with each other).
local oo = require "loop.simple" local UnorderedArray = require "loop.collection.UnorderedArray" Scheduler = oo.class({}, UnorderedArray) function Scheduler:run() while #self > 0 do local i = 1 repeat local thread = self[i] coroutine.resume(thread) if coroutine.status(thread) == "dead" then self:remove(i) else i = i + 1 end until i > #self end end function thread(name) return coroutine.create(function() for i=1, 3 do print(string.format("%s: add '%s'", name, name..i)) scheduler:add(coroutine.create(function() for step=1, 3 do print(string.format("%s: step %d of 3", name..i, step)) coroutine.yield() end end)) end end) end scheduler = Scheduler{ thread("A"), thread("B"), thread("C") } scheduler:run()
Copyright (C) 2004-2008 Tecgraf, PUC-RioThis project is currently being maintained by Tecgraf at PUC-Rio.