Iterating through nil values

Posted by Flelm on Thu 13 Apr 2006 08:57 PM — 2 posts, 12,524 views.

#0
First off: This is an IRE mud I'm trying to develop a "curing system" for. Just thought I'd get that out of the way.

Basically, what I want to do is create a large table with the various afflictions that can be caused (blindness, broken legs, etc), their cures, whether they're active or not, etc. However, the one addition I'm not sure the feasibility of is a "priority" value.

This is what I was thinking of: First is to set the parent array's key to priority. e.g., affliction[1] is the thing I want to cure first if I have it, affliction[2] second, etc.

There's two problems with that. I want to be able to shuffle afflictions around if possible, so I'd likely make it affliction[1], affliction[10], affliction[20], etc for the initial values. What kind of performance hit can I expect for transversing the nil values (such as affliction[2]-affliction[9])? Or is there a way to skip them completely? Secondly, I'll take a performance hit when I try to update an affliction, as I can't access the afflictions directly, unless I use an external linked list that relates the priority numbers to their afflictions.

In summary, what kind of performance hit will I be looking at should I if I iterate through this array say... 3-4 times a second? Secondly, is there a better way to do this? I know at least some people here have experience on IRE MUDs.

Thanks in advance.

EDIT:

Would a better solution be to do something similar to this?


afflictions = {}

-- Structure for aff_list
-- "affliction name" = "cure function", active (int)

aff_list = {

"aeon" = {"curewith_purge", 0},
"stupidity" = {"curewith_herb", 0},
etc
}


And then, for example, when I gain the stupidity affliction with an empty "affliction" table:

aff_list["stupidity"][2] = 1
afflictions[1] = aff_list["stupidity"]


What kind of problems am I looking at here?
Amended on Thu 13 Apr 2006 09:27 PM by Flelm
USA #1
Your performance hit will be massively negligible. Lua can iterate through hundreds of thousands of items in less than a second, so iterating over a measly 20 or 50 or 100 even 10 times a second won't hurt you at all.

To prove it to you, here is a sample Lua program:
#!/usr/bin/lua

mytab = {}
for i = 1, 100000 do
    mytab[i] = i
end

for i,v in pairs(mytab) do
    if mytab[i] == nil then print "oh no" end
end


I time the execution:
$ time lua iter.lua 

real    0m0.156s
user    0m0.156s
sys     0m0.030s


It took 156 milliseconds to iterate over 100,000 elements twice (so 200,000 iterations), making one assignment and one check per element.

I increased the number to 900,000 and got this:
$ time lua iter.lua 

real    0m0.531s
user    0m0.390s
sys     0m0.093s

As you can see, it only took 531 milliseconds to iterate over 900,000 elements twice (so 1,800,000 iterations).

So, in your case, there is really no problem at all. :-)