String Array

BlitzPlus Forums/BlitzPlus Beginners Area/String Array

thepalegreenhorse(Posted 2013) [#1]
Could some kind and clever soul show me how to:

Create a string array containing, say, three words;
Randomly select (and print) one of those three words.

Alternatively, is there a related tutorial anywhere on the www? Blowed if I can find anything relevant! :)

A thousand thanks.


Yasha(Posted 2013) [#2]
Well, to create an array:

;Either
Dim words$(2)
;Or
Local words$[2]


(The main difference is that Dim arrays can be resized, but they are limited in number and utility; try to use the other kind where possible.)

Populate it with words (using the second one from here on out):

words[0] = "Foo!"
words[1] = "Bar!"
words[2] = "Baz!"


Randomly generating a number can be done with Rand:

Local num = Rand(0, 2)


So to print at random:

Print words[Rand(0, 2)]


To use a Dim array instead (necessary if you're following old tutorials), just use parentheses instead of square brackets, and obviously the first rather than second declaration at the top.


Rand (and Rnd) has a hidden internal "seed" number that determines what the next number it returns will be. To get different results from run to run, this means you need to "seed" it with an unpredictable value. MilliSecs() is normally used for this because it's completely unknown to the program, and unreproducible (it returns how long the computer has been on, measured in milliseconds).

The reason Rand a) provides such functionality, and b) demands you use it, is because sometimes you do actually want to recreate "random" behaviour for later reuse (e.g. Minecraft's "world seeds" are literally this). All normal RNGs have this feature.


thepalegreenhorse(Posted 2013) [#3]
Thanks so much Yasha! Really appreciated.
Could the same result be achieved using READ, RESTORE and DATA? I don't get the distinction.


Yasha(Posted 2013) [#4]
Read/Restore/Data are legacy commands, best ignored for the most part. They exist for compatibility with older BASIC dialects. What they do is define blocks of constant data in your application's binary that can be accessed later... but the data can't be modified at runtime and there is no way to index it numerically (you can't choose a block by index, and you have to read through its data element-by-element too), so frankly they're pretty useless compared to just writing code like this.

There are several areas in BlitzPlus where legacy features overlap with more modern ones (the two kinds of array is another example). In general the legacy features lead to inferior code and you should avoid them, although there are occasionally some good reasons for them (e.g. the fact that Dim arrays can be resized is occasionally very handy, if never strictly necessary).