Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Choosing at random from an array

I haven't used arrays before, and for some reason find them a tad daunting. This page:

http://www.glorioustrainwrecks.com/node/5034

tells me much of what I need to know, but how can I fetch a random item in the array, as opposed to specifying one?

Comments

  • See if this dog will hunt:
    <<set $array = ["foo", "bar", "baz", "qux"]>>
    <<set $length = $array.length>>
    <<set $i = Math.floor(Math.random()*$length)>>
    <<print $array[$i]>>
    [[Start][state.restart()]]
  • If you're using SugarCube, there is an included function to pick a random element from an array.
  • @Sharpe Good thinking!

    @mth I am using Sugarcube, and I really should have checked the docs before posting. D'oh!

    Thanks both! ;D
  • No problem.

    I don't know what my reluctance to jump on the SugarCube train is. I just dislike working with (fighting) headers and I'm scared it will increase my frustration rather than decrease it since it seems so much more robust than 'Cane.

    That save function, though. Man, do I need it.

    If CoraBlue were still aroundI miss her so badI would make the leap.
  • In what way do you think you'd be fighting it? Are you doing something crazy complex and Sugarcane-specific?
  • I don't know about crazy complex, but attached is a screen shot of the foundation of my current project, one of three or so turn-based RPG's. It will double or triple in size when I actually get into making it a "real game."

    I don't know how much work it would take to "convert" it to SugarCube . . .
  • In Twine 1.4.2, you will be able to supply an array to the either() function to retrieve a random element from it. For instance: either($array).
  • @Sharpe - You should be okay. Unless your CSS is as messy as mine, the main annoying thing you'll need to do is initialise your variables to 0. Give it a go, anything that doesn't work should be a simple "find and replace" fix. Hopefully! :)
Sign In or Register to comment.