mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-25 23:24:35 +00:00
[modified] unique_mapping memoised compare function and cleanup
This commit is contained in:
parent
4a2505a04d
commit
28e06c4a10
@ -1,6 +1,10 @@
|
|||||||
--generate a mapping from unique values to plain numbers
|
--[[
|
||||||
--useful for arbitrarily ordering things that don't have
|
unique mapping
|
||||||
--a natural ordering implied (eg textures for batching)
|
|
||||||
|
generate a mapping from unique values to plain numbers
|
||||||
|
useful for arbitrarily ordering things that don't have
|
||||||
|
a natural ordering in lua (eg textures for batching)
|
||||||
|
]]
|
||||||
|
|
||||||
local unique_mapping = {}
|
local unique_mapping = {}
|
||||||
unique_mapping._mt = {
|
unique_mapping._mt = {
|
||||||
@ -13,6 +17,7 @@ local _MAP_VARS = setmetatable({}, {
|
|||||||
__mode = "k" --only keys are weak
|
__mode = "k" --only keys are weak
|
||||||
})
|
})
|
||||||
|
|
||||||
|
--create a new unique mapping
|
||||||
function unique_mapping:new()
|
function unique_mapping:new()
|
||||||
local r = setmetatable({}, self._mt)
|
local r = setmetatable({}, self._mt)
|
||||||
--set up the actual vars
|
--set up the actual vars
|
||||||
@ -22,12 +27,15 @@ function unique_mapping:new()
|
|||||||
return r
|
return r
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--private;
|
||||||
|
--get the next index for this mapping
|
||||||
function unique_mapping:_increment()
|
function unique_mapping:_increment()
|
||||||
local vars = _MAP_VARS[self]
|
local vars = _MAP_VARS[self]
|
||||||
vars.current_index = vars.current_index + 1
|
vars.current_index = vars.current_index + 1
|
||||||
return vars.current_index
|
return vars.current_index
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--get or build a mapping for a passed value
|
||||||
function unique_mapping:map(value)
|
function unique_mapping:map(value)
|
||||||
local val = self[value]
|
local val = self[value]
|
||||||
if val then
|
if val then
|
||||||
@ -38,4 +46,17 @@ function unique_mapping:map(value)
|
|||||||
return i
|
return i
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--get a function representing an a < b comparision that can be used
|
||||||
|
--with table.sort and friends, like `table.sort(values, mapping:compare())`
|
||||||
|
function unique_mapping:compare()
|
||||||
|
-- memoised so it doesn't generate garbage, but also doesn't
|
||||||
|
-- allocate until it's actually used
|
||||||
|
if not self._compare then
|
||||||
|
self._compare = function(a, b)
|
||||||
|
return self:map(a) < self:map(b)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return self._compare
|
||||||
|
end
|
||||||
|
|
||||||
return unique_mapping
|
return unique_mapping
|
||||||
|
Loading…
Reference in New Issue
Block a user