Parse a string as an array

Is it possible to represent a string variable as an array?

For example, if I have the variable:

*temp string "test"

Can I transform it so that I can have each character as an element of an array, so it’s equivalent to the declaration below?

*temp_array string 4 "t" "e" "s" "t"

*temp string “test”
*temp_array temp_array 4 “”
*set temp_array#1 string.charAt(1)
*set temp_array#2 string.charAt(2)
*set temp_array#3 string.charAt(3)
*set temp_array#4 string.charAt(4)

  • Basically create a string variable called “string” and assign it the value “test”

  • Then create an array called “temp_array” with 4 elements, each to an empty string.

  • Finally, use the *set command to assign each character of the string to an element of the array using the charAt function.

It looks like ChoiceScript doesn’t know about the charAt function (I assume it’s valid in vanilla JavaScript). However, I did some digging around the CSLib files and found it has methods for obtaining characters out of strings. Namely,

*set result &(string#3)

this would put the third character of the variable string in result. However, I haven’t found any documentation on the & and # operators on the official CS wiki.

@CJW @cup_half_empty Is there any place I can find documentation about these operators? Also, if I use them, will I be able to publish the game via Hosted Games, or is it considered a “forbidden API”?

2 Likes

I don’t know if there’s documentation about them. Your best bet is this forum. The wiki is maintained by the community and it isn’t up to date. I found the operators by looking at ChoiceScript’s source code and other people’s code. They are not prohibited and it won’t prevent you from publishing your game.

  • &: string concatenation

Used to “add” (concatenate) two strings together.

*set myVar "Hello, " & "World" 
*print myVar

This will output Hello, World.

  • #: index access for string

This is exclusive for string. You can access the character at a certain index (1-based).

*set myVar "Hello, World" # 1
*print myVar

This will output H.

  • Compound Assignment

If you start an assignment with an operator it will use the original value of the variable as the left hand side of the operation.

*temp myVar 1
*set myVar +1

The value of myVar should be 2 now. It’s the same as doing something like:

*temp myVar 1
*set myVar myVar + 1

Or, in other programming languages:

let myVar = 1;
myVar += 1;

I suggest using CSLib, it was meant to abstract the complex logic into simple interfaces.

3 Likes

Thank you! The indexing operator is exactly what I needed.

2 Likes

This topic was automatically closed 24 hours after the last reply. If you want to reopen your WiP, contact the moderators.

For future readers, these operators are actually documented on the wiki to some extent:

Though evidently not very easy to find!

4 Likes