Page 1 of 1

How I can get index of array element

Posted: Thu Aug 10, 2017 4:58 pm
by sashapont
I have table
array${"one","two","three"."..."}


How I can get index "two"?

Re: How I can get index of array element

Posted: Thu Aug 10, 2017 6:32 pm
by SamuraiCrow
When you need a reverse lookup for the entries in one array, you need an index table. You can make one like this:

Code: Select all

Reverse={}
For Key,Value In IPairs(array$) Do Reverse[Value]=Key
Then you can find the index of a value by looking in the Reverse table.

Re: How I can get index of array element

Posted: Thu Aug 10, 2017 8:20 pm
by Bugala
To add to SamuraiCrows comment.

There is no direct way to get index number, but you have to use some sort of search function (as example SamuraiCrows example) to find the item, and when you find the item, then mark up the index number.

However, if you have two different indexes both holding "two" inside them, you might end up getting either one of them, depending how you make your search and locate function.

If each item is unique, that there is always only one "two" inside the table, then you could also use two different tables:

Code: Select all

TableA = { "fee", "faa", "foo"}
TableB = { ["fee"] = 1, ["faa"] = 2, ["foo"] = 3 }

indexnumber = tableB["fee"]
debugprint(TableA[indexnumber])
would result in fee being printed out.

Re: How I can get index of array element

Posted: Fri Aug 11, 2017 11:25 am
by SamuraiCrow
@Bugala

Don't Array indexes start at 0?

Re: How I can get index of array element

Posted: Fri Aug 11, 2017 12:01 pm
by Bugala
@SamuraiCrow

yes, mistake in my example.