How I can get index of array element

Discuss any general programming issues here
Post Reply
sashapont
Posts: 113
Joined: Thu Aug 03, 2017 2:49 pm

How I can get index of array element

Post by sashapont » Thu Aug 10, 2017 4:58 pm

I have table
array${"one","two","three"."..."}


How I can get index "two"?

SamuraiCrow
Posts: 213
Joined: Fri May 15, 2015 5:15 pm
Location: Ft. Collins, Colorado USA

Re: How I can get index of array element

Post by SamuraiCrow » Thu Aug 10, 2017 6:32 pm

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.

Bugala
Posts: 757
Joined: Sun Feb 14, 2010 7:11 pm

Re: How I can get index of array element

Post by Bugala » Thu Aug 10, 2017 8:20 pm

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.

SamuraiCrow
Posts: 213
Joined: Fri May 15, 2015 5:15 pm
Location: Ft. Collins, Colorado USA

Re: How I can get index of array element

Post by SamuraiCrow » Fri Aug 11, 2017 11:25 am

@Bugala

Don't Array indexes start at 0?

Bugala
Posts: 757
Joined: Sun Feb 14, 2010 7:11 pm

Re: How I can get index of array element

Post by Bugala » Fri Aug 11, 2017 12:01 pm

@SamuraiCrow

yes, mistake in my example.

Post Reply