[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: keying by function and index
- From: "Nick Trout" <nick@...>
- Date: Fri, 16 May 2003 16:56:42 -0700
> > Hi, I need to be able to use functions as keys in a table but
> > also need
> > to associate different indexed values for each function. I
> could go
> > with keying first by function then via the index in
> > sub-tables, but for
> > my particular use it would be better to have all of the
> > references in a
> > single table. Would it be good then to key by a string with
> > the index
> > appended? Something analagous to this:
> >
> > local function f() end
> > local index = 3
> > local value = "foo"
> > local t = {}
> > t[tostring(f) .. "_" .. index] = value
>
>
> Untested:
>
> T = {}
>
> function setvalue(fn, index, value)
> if not T[fn] then T[fn] = {} end
> T[fn][index] = value
> end
>
> function getvalue(fn, index)
> return T[fn][index]
> end
Oops I didn't read you're mail very thoroughly did I? Its true, us men
cannot multitask!
What is the range of these indices? Could you look up the fn in a table?
E.g.
T, TI = {}, {}
COUNT = 1, RANGEMAX = 1000
function setvalue(fn, index, value)
assert(index>=0 and index<RANGEMAX)
if not TI[fn] then TI[fn] = RANGEMAX*COUNT; COUNT=COUNT+1 end
T[TI[fn] + index] = value
End
function getvalue(fn, index)
assert(index>=0 and index<RANGEMAX)
return T[TI[fn] + index]
end
i.e. use a look up table to map fns to indice base ranges and add
specific index. If you do it your way you are generating loads of
strings which is inefficient processing wise and in memory use and GC.
Nick