A couple of utility constructors

I notice that in a lot of example code for ShowMenu, the Split function is used to generate a stringlist; but there's no equally easy way to make other types of data structures.

I use functions like these quite often (especially for easy testing), and I figure I should share them in case anyone else finds them useful.

Stringlist

We've already got Split for this.

Objectlist

Usage: characters = GetObjectlist ("player;bob;eve;ivy")

<function name="GetObjectlist" params="input" type="objectlist">
  output = NewObjectList()
  foreach (obj, Split(input)) {
    list add (output, GetObject(obj))
  }
  return (output)
</function>

Arbitrary lists

Maybe not so useful to many people; but I quite often end up needing a list of numbers, or a list whose members are of different types. Easiest way to do that:

Usage: somelist=SplitEval("7;5;3;game.pov;\"string element\";SomeFunction()")

<function name="SplitEval" params="input, params" type="list">
  output = NewList()
  if (not IsDefined("params")) {
    params = NewDictionary()
  }
  foreach (expr, Split(input)) {
    list add (output, Eval(expr, params))
  }
  return (output)
</function>

Stringdictionary

This could be useful to give the arguments to ShowMenu in a conversation system.

Usage: mydict = SplitDict("greeting=Hello, how are you today?;weather=Have you noticed that it's raining a lot the last few days?;exit=Sorry, no time to chat. See you around.")

<function name="SplitDict" parameters="input" type="stringdictionary">
  output = NewStringDictionary()
  foreach (expr, Split(input)) {
    pos = Instr (expr, "=")
    if (pos = 0) {
       if (not DictionaryContains(output, expr)) dictionary add (output, expr, "")
    }
    else {
      DictionaryAdd (output, Left (expr, pos-1), Right (expr, LegthOf(expr) - pos))
    }
  }
  return (output)
</function>

Objectdictionary

Usage: objectdict = GetObjectdict("key1=objectname1;key2=objectname2;key3=objectname3")

<function name="GetObjectdict" params="input" type="objectdictionary">
  output = NewObjectDictionary()
  foreach (obj, Split(input)) {
    parts = split (obj, "=")
    if (ListCount (parts) = 2) {
      dictionary add (output, parts[0], GetObject(parts[1]))
    }
    else {
      error ("Invalid element “"+obj+"” passed to GetObjectdict")
    }
  }
  return (output)
</function>

Arbitrary dictionary

You can already do this using QuickParams, up to a certain number of elements.

<function name="SplitDict" parameters="input, params" type="dictionary">
  output = NewDictionary()
  if (not IsDefined("params")) {
    params = NewDictionary()
  }
  foreach (expr, Split(input)) {
    pos = Instr (expr, "=")
    if (pos = 0) {
       if (not DictionaryContains(output, expr)) dictionary add (output, expr, null)
    }
    else {
      DictionaryAdd (output, Left (expr, pos-1), Eval (Right (expr, LegthOf(expr) - pos), params))
    }
  }
  return (output)
</function>

Log in to post a reply.

Support

Forums