How to deal with arrays

Thank you for bumping this @LAM, it made me realise there’s actually some more options for the toolkit available now (though still no ideal one).

This isn’t targeted at you specifically, I just wanted to add it for anyone else who comes looking :slightly_smiling_face:

So below follows a couple more array related options.


Array Creation Patch

I wrote a patch adding *create_array and *temp_array commands to ChoiceScript. It's not merged (unfortunately) but those more comfortable with CS and git could use it to patch their own copies.

See: Add *create_array, *temp_array, *delete_array by CareyJWilliams · Pull Request #136 · dfabulich/choicescript · GitHub.

Pros

  • Keeps to ChoiceScript (mostly)
  • Sticks to standard array semantics (in CS)
  • Reduces effort of initialising arrays

Cons

  • Unsupported by CoG (at the time of writing)
  • No variable length arrays

The ChoiceScript Library (CSLIB)

See: 🧰 [TOOL] CSLIB - ChoiceScript Library

Contains support for both ‘arrays’ and ‘loops’ to some extent.

For loops there is a routine called ‘repeat’ which takes a scene+label ref to a routine, and repeatedly passes it a number up to a limit. You can use the following idiom (NEVER is a constant variable always set to false) to make your CS look reasonably close to a standard for loop:

*gosub_scene cslib_util repeat "startup" "print_numbers" 5
*if (NEVER)
    *label print_numbers
    *params n
    ${n}
    *return

Arrays are still a pain to create (unless you use them in conjunction with the patch above), but they are a lot easier to work with in CSLIB:

*comment create empty array
*create player_name_1 ""
*create player_name_2 ""
*create player_name_3 ""
*create player_name_4 ""
*create player_name_5 ""
*create player_name_6 ""
*create player_name_7 ""
*create player_name_8 ""
*create player_name_9 ""
*create player_name_10 ""
*create player_name_count 0
*create player_name_max 10

*comment populate
*gosub_scene cslib_array set_from "player_name" 1 "Jack" "Janet" "Jericho" "Joseph"
*gosub_scene cslib_array push "player_name" "Jack"
*gosub_scene cslib_array push "player_name" "Jemma"

*comment merge to a sring and print
*gosub_scene cslib_array join "player_name" ", "
${player_name_count} player names: ${cslib_ret}

Pros

  • 100% ChoiceScript
  • You get array methods for free: push, pop, filter, etc.
  • Helps with code structure / readability
  • CSLIB is well-tested, whereas custom code wouldn’t necessarily be
  • Variable length arrays (kinda: they have a max, but this can be set as high as you need)

Cons

  • Arrays are still a pain to define (unless you combine with above)
  • Requires CSLIB / an external dependency
  • Less performant
5 Likes