Skip to main content
Known Participant
November 30, 2019
Answered

getting the length of an array from a Text-File?

  • November 30, 2019
  • 2 replies
  • 1083 views

Hi,

 

I am looking for a way of outputing a random word or group of words from a textfile.

I have gotten so far using $.evalFile expression to output text from a .txt file:

 

My .txt could look like this:

text1 = "word1";
text2 = "word2";
text3 = "word3";
text4 = ["word4", "word5", "a group of words", "another word"];

 

For text1-3 I can make a textlayers which are also called text1, text2, text3 and give them the Expression:

$.evalFile("/Users/rene/Desktop/AE\ TEST/sourcetext.txt");
eval(thisLayer.name)

 

For text4 I wrote:

r = Math.floor(random(3));
$.evalFile("/Users/rene/Desktop/AE\ TEST/sourcetext.txt");
eval(thisLayer.name)[r]

 

That works so far. But how can I write the Expression in a way, that it automatically recognizes the length of the text-array (= knowing how many elements there are to choose from) and put this into the random()?

 

thank you!

 

This topic has been closed for replies.
Correct answer Dan Ebberts

Try it this way:

 

$.evalFile("/Users/rene/Desktop/AE\ TEST/sourcetext.txt");
r = Math.floor(random(eval(thisLayer.name).length));
eval(thisLayer.name)[r]

 

Dan

2 replies

Martin_Ritter
Legend
December 1, 2019
Known Participant
December 1, 2019

Guess what:

Googled, got the first part done. Googled further (basically with the same search you wisely adivsed), didn't get it done.

Used my last 10% and used the forum....

 

 

Martin_Ritter
Legend
December 1, 2019

Umm, okay.

Getting the length of an array is just such a basic task, that I was wondering how somebody how knows what an array is can't get this done.

 

I recommend stackoverflow (https://stackoverflow.com/) - that's a great ressource for coding questions. And usual people are posting code snippets so you can see how the function or method is applied and what the syntax have to look like. I always end up on stack overflow when I google my coding questions.

 

*Martin

Dan Ebberts
Community Expert
Dan EbbertsCommunity ExpertCorrect answer
Community Expert
November 30, 2019

Try it this way:

 

$.evalFile("/Users/rene/Desktop/AE\ TEST/sourcetext.txt");
r = Math.floor(random(eval(thisLayer.name).length));
eval(thisLayer.name)[r]

 

Dan

Known Participant
December 1, 2019

Hi Dan,

 

thanks a lot! That works perfectly!