Thursday, January 13, 2011

Dynamicism with Context Preservation

In my last post I talked about changing some code in real time. One of the problems with my current approach was the loss of the program context. If we are using my Scalabot example, this means that I can make no changes to ScalaBot from the dynamic portions, not dynamic calls, etc. I was limited to interacting with a constant data store. I have since tweaked my library which allows for context preservation, if context is important to the dynamic call.

The signature changed from:

dynamic('symbol) {
  // Block of code
}

To:

dynamic('symbol, Context("variable" -> variable)) { ctx =>
  // Block of code
}

// Or if context is unimportant
dynamic('symbol) { ctx =>
  // Block of code
}

The update signature hardly changed. A context is always passed into a dynamic block now. It could be an empty context, but a context nonetheless.

update('symbol) { ctx =>
  if(!ctx.params.isEmpty) {
    // Grab stuff from context, and operate
    val x = ctx("variable")
    // do something with x
  }
}

I'll show you how I used it to turn my ScalaBot against its master. It's always more fun to witness the AI get a mind of its own, and destroy everything. Taking a look at the dynamic block from yesterday, let's preserve the context.

dynamic('message, Context("bot" -> this, "sender" -> sender)) { ctx =>
  println("A message posted from %s" format(sender))
}

Once again, I chatted a couple times, before I turned my bot against me.

import ircbot.ScalaBot
import hotcode.HotSwap._

object Main extends Application {
  update('message) { ctx =>
    val bot: ScalaBot = ctx("bot")
    val sender: String = ctx("sender")

    sender match {
      case "schmee" => bot.sendMessage("#pircbot", "schmee is a loser. Don't listen to him")
      case _ => println(sender)
    }
  }
}

Screenshot

This time I truly changed the bot's behavior, because I have a reference to the bot itself. I knew before going into this, that the presentation of this library would take a hit, but I thought the end result was worth it. I've decided to sell this library a little differently. It's more of a remote control library. Hot swapping is not possible with it, but I like what it does.

I have an idea of some additional code to allow more remote controlling. Will get to that later.

-- Philip Cali

No comments:

Post a Comment