How I can get index of array element

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

How I can get index of array element

Post by sashapont »

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


How I can get index "two"?
SamuraiCrow
Posts: 475
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: How I can get index of array element

Post 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.
I'm on registered MorphOS using FlowStudio.
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Re: How I can get index of array element

Post 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.
SamuraiCrow
Posts: 475
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: How I can get index of array element

Post by SamuraiCrow »

@Bugala

Don't Array indexes start at 0?
I'm on registered MorphOS using FlowStudio.
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Re: How I can get index of array element

Post by Bugala »

@SamuraiCrow

yes, mistake in my example.
Post Reply