lua-users home
lua-l archive

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

2011/10/18 Victor Young <>:
> It seems to be a simple and flexible method, thank you and Enrico

I append another solution to this solved problem :-)

-- history.lua
-- Usage:  history = require "history"
--   the function call 'history()' returns an empty table such that 
--   'pairs' preserves historical order of items added to it
-- Restrictions: 
--    don't use the key '__keys'
-- Bugs masquerading as features:
--    the historical position of a key is remembered even if nil is
--    assigned as its value
--    if another assignment to a deleted key is made, the key appears
--    at both places in the history (but with the same value)
-- Dirk Laurie 2011-10-18  
-- LICENCE: Public domain

local function history()
    local t = {__keys={}}
    setmetatable (t,{ 
      __newindex = function(self,index,value)
        local keys = self.__keys
      __pairs = function(self)
        local i=0
        return function() 
                 local k=self.__keys[i]
                 return k, rawget(self,k)
    return t

--[[  Example
-- Add another hyphen to previous line to run the example
t = history()
t.a = 'A'
t.z = 'Z'
t[1] = '1'
t[3] = '3'
t[2] = '2'

for k,v in pairs(t) do print(k,v) end

return history