Page 1 of 1

A small question about accessing a character in a string

Posted: Thu Feb 11, 2021 6:03 pm
by PlaidFlannel
I have an array variable with a range of different kinds of data in the array elements. One element, call it myArray["identity"], contains a text string.

To access a particular character in that string, I would write code like this:

Code: Select all

if char 5 of myArray["identity"] is "X" then ...
However, as a LiveCode beginner, I reverted to habits from other programming languages and inadvertently wrote code like this:

Code: Select all

if myArray["identity"][5] is "X" then ...
This code was not flagged as an error, and it seemed to execute correctly. In fact, I didn't even discover this unusual code until about two weeks after writing it.

I've not been able to find a small test case to demonstrate this. So my conclusion is that this code might not cause an error, but it always yields empty as a result, and, coincidently, empty was an acceptable value at that point in my project.

Is there another explanation?

Re: A small question about accessing a character in a string

Posted: Thu Feb 11, 2021 6:14 pm
by Klaus
Hi PlaidFlannel,

Code: Select all

if myArray["identity"][5] is "X" then ...
this will check if the content of -> myArray["identity"][5] = X
But this key does not exist! However LC will not complain when we try
to access non-existent keys of an array, that is the reason!

So this is the way to go, since it will check the content of -> myArray["identity"] for the character = X

Code: Select all

if char 5 of myArray["identity"] = "X" then ...
Best

Klaus