Page 1 of 1

foreach to tell its location

Posted: Fri Jul 07, 2017 10:53 pm
by Bugala
I have many times encountered a situation where I have had to change "foreach" loop into "for n=1 to x" loop, because i have been in need of knowing the location.

as example:

Code: Select all

foreach(table, function(key, item)
                                                 if item = searchedthing then removeitem(table, ???)
                                endfunction)
this example is naturally not very good as you shouldnt remove stuff in middle of loop, but just to give you the idea.

For reasons like this, it would be handy to have something like "WhatIndexIsIt()" command which would tell at what index location it is currently going at.

Re: foreach to tell its location

Posted: Sat Jul 08, 2017 8:19 pm
by SamuraiCrow
What's wrong with the For .. In .. Do syntax? It looks like this:

Code: Select all

For key,item in IPairs(table)
   ...
Next
In this example, key tells where and item tells what.

Re: foreach to tell its location

Posted: Sat Jul 08, 2017 8:25 pm
by Bugala
ah, thanks. I had forgot that exists. I now rememebr i once before was looking for same problem and either someone suggested or found myself pairs existed, but must have forgot it existed.

Solves the problem.