lua-users home
lua-l archive

Re: table iteration problem

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


2011年10月18日 Victor Young <littlehaker@gmail.com>:
> It seems to be a simple and flexible method, thank you and Enrico
I append another solution to this solved problem :-)
Dirk
-- 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
 keys[#keys+1]=index
 rawset(self,index,value)
 end;
 __pairs = function(self)
 local i=0
 return function() 
 i=i+1
 local k=self.__keys[i]
 return k, rawget(self,k)
 end
 end})
 return t
 end
--[[ 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

AltStyle によって変換されたページ (->オリジナル) /