Debugging Tutorial: Difference between revisions

From RPTools Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 187: Line 187:
--[[User:Wolph42|Wolph42]] 09:14, 7 June 2012 (UTC)
--[[User:Wolph42|Wolph42]] 09:14, 7 June 2012 (UTC)
===cheater you have been reported===
===cheater you have been reported===
This 'functionality' is embedded to prevent cheating...obviously, however this can also result in this error message (and only this error message) in your own code! This typically happens when you do not port code results straight to the chat, but first store them inside a variable and at the end port that variable to the chat. This is usefull for when you e.g. want to use [h:broadcast(macro_output)] as it allows for more control over the output. Fortunately its not very easy to get this error. One way of letting this occur is by using [[evalmacro|evalmacro()]]
This 'functionality' is embedded to prevent cheating...obviously, however this can also result in this error message (and only this error message) in your own code! This typically happens when [[broadcast|broadcast()]] the result of an [[evalmacro|evalmacro()]] call, where the evalmacro result contains « guillemonts »: . E.g. paste this into your chat:
  [h:result = evalmacro(decode("4 The attack scoops out one of the target's eyes, inflicting <b>[Fat=1d5] level(s) of Fatigue"))]
  [h:broadcast(result)]
To debug this I store 'result' in a lib:token property before I do the broadcast. From the text its usually easy to find where the guillemonts have entered. So:
  [h:result = evalmacro(decode("4 The attack scoops out one of the target's eyes, inflicting <b>[Fat=1d5] level(s) of Fatigue"))]
  [h:setLibProperty("debugOutput", result, "lib:Token")]
  [h:broadcast(result)]
Then after running the macro I can copy paste that property inside a text editor and track down the guillemonts.

Revision as of 12:22, 7 June 2012


ADVANCED
THIS IS AN ADVANCED ARTICLE

Debug Methods For Maptool Scripting

A tutorial to squash little critters from your MT code.

What is this about?

I've been working with MT for over 2 years now and I can still remember the initial struggle I had due to the lack of any debugger. As it turns out there are quite a few methods to debug your code but unfortunately they're not very obvious to find. So here a short summary of available tools.

I've marked this article as 'advanced' as it does assume that you know the basics of MT script, like Library Token, onCampaignLoad and User defined functions.

Pause

The most basic and I think most used method is the 'Pause' method as developed by zeAl. The only way in MT to interrupt the flow of the code is with the use of input(). zeAl created some clever code around input() to use for debugging. His full contribution can be found here: [1]. Its working is simple as shown in this example:

  [h:strength = 5]
  [h:toughness = 10]
  [h:pause("strength", "toughness")]
  [r:"This text you'll see AFTER the pause"]

The running code will stop after the toughness=10 line, show the two variables both name and value and after you've clicked ok the code will continue. Its possible to just run

 [h: pause()]

in several places in your code so you can check where it crashes.

In order for pause to work in your campaign you will need a library token with an onCampaignLoad macro containing the following line:

  [ defineFunction("pause", "pause@this", 1, 0 ) ]

and you will also need a macro called 'pause' on the same library token containing the following code:

    [ toolkit.DebugVariableCount = argCount() ]
    [ toolkit.DebugInputParameter = ".|<html>" +
        "<table cellspacing='2' cellpadding='0' style='background-color:#595751'>" +
        "<tr><td>" +
        "<table width='300px' cellspacing='0' cellpadding='2' style='background-color:#FAF9F5;'>" +
        "%{toolkit.DebugVariableRows}</table></td></tr></html>" +
        "|Debugger|LABEL|SPAN=TRUE"
    ]
    [ toolkit.DebugVariableRow = "<tr %{toolkit.DebugVariableRowStyle}><td>" +
        "<b>%{toolkit.DebugVariableName}</b></td><td>%{toolkit.DebugVariableContent}" +
        "</td></tr>"
    ]
    [ toolkit.DebugVariableRows = "<tr style='background-color:#E0DDD5; font-size:1.1em;'><td><b>Variable</b></td><td><b>Value</b></td></tr>" ]
    [ count( toolkit.DebugVariableCount ), code:
    {
        [ toolkit.DebugVariableRowStyle = "" ]
        [ toolkit.DebugVariableName = arg( roll.count ) ]
        [ toolkit.DebugVariableContent = eval( arg( roll.count ) ) ]
        [ if( floor( roll.count/2 ) == roll.count/2 ), code:
        {
            [ toolkit.DebugVariableRowStyle = "style='background-color:#EDECE8;'" ]
        } ]
        [ toolkit.DebugVariableRows = toolkit.DebugVariableRows +
            strformat( toolkit.DebugVariableRow )
        ]
    } ]
    [ if( toolkit.DebugVariableCount == 0 ), code:
    {
        [ toolkit.DebugVariableRows = "<tr><td style='font-size: 1.4em' align='center'><b>Pause</b></td></tr>" ]
    } ]

    [ toolkit.DebugBreak = input( strformat( toolkit.DebugInputParameter ) )]
    [ abort( toolkit.DebugBreak ) ]

You can also find this code after the above link to zeAl's post.

Tip: if you want to copy paste the above code or the code from the post, then FIRST paste it into a simple text editor and copy it from there and THEN paste it into the MT macro. This prevents from unintentional copying e.g. linefeeds (0x0A).

Where pause goes wrong

A couple of useful things to know when you start using pause().

  • if you use it at the top of your macro to e.g. check the values of the passed on arguments like this:
  [tmp = macro.args]
  [pause("tmp")]
  [var1 = arg(0)]
  [var2 = arg(1)]

then arg(0) will no longer exist!! The value that macro.args contain changes as soon as pause has run as it has its own scope and redefines it. Usually this can lead to inexplicable errors so be ware of this! Its better to use it like this:

  [tmp = macro.args]
  [var1 = arg(0)]
  [var2 = arg(1)]
  [pause("tmp")]
  • pause can only handle very simple html code, so if you want to debug a dynamic form which you have assigned to a variable I would suggest you use a combination of the Show_HTML method and put a pause() right after that.

The log file

Going to a slightly more advanced method you can start using the log file. First off if MT crashes you can always check the log.txt file which is located in your .maptool directory (varies per OS where that is, for win7 its: C:[username]\.maptool). You will also find a 'logging.xml' file in that directory. The XML file tells maptools what to send to the log.txt file. Per default MT install this will only log generated errors. You can however also replace this file from the one that you can find in the maptool install directory (the one you unzipped initially). In the directory 'Misc' you find a 'macros-logging.xml' file. You can replace the existing XML file in your .maptool directory with that one (don't forget to rename it to logging.xml !) and it will log ALL macro code. This can render into a HUGE log file and slows down MT a bit so be careful with it. In my case I have a PC and Laptop, the laptop I use for running the games, so no logging, the PC I use for coding so logging is always turned on on that PC. If your code crashes or generates weird errors, you can check the log file to see where it went wrong.

The Console

The console is the real kicker, I found out about this after a year or so and since I'm aware of it it has made coding and debugging in MT SO MUCH SIMPLER!!. To activate it you need to do 2 things

  • first you need to replace the logging.xml file with the macro-logging.xml as described here above.
  • second you need to edit your mt.cfg file. This file you will find in the install directory. The content will look like something like this:
 MAXMEM=1024
 MINMEM=64
 STACKSIZE=4
 JVM=C:\Program Files\Java\jre6\bin\javaw
 PROMPT=true

depending on your settings and OS. You need to remove only ONE letter: the 'w' from 'javaw'. So it becomes

 JVM=[what it reads here differs per OS]java

Now you will have a console which shows the MT script real-time. Combine this with strategically placed pause()'s and debugging becomes a breeze. Here's my usual screen layout when I'm debugging:

Notes:

  • Text and comment is NOT ported to the console. So
  Hello world
  <!-- this is comment -->

won't show in the console nor in the log, however:

  [r:'Hello world']
  [h:'<!-- this is comment -->']

will show up! Note though the latter is slower then the former to execute (which becomes noticeable around 200 to 400 of these lines, so not much to worry about).

  • I personally find it very useful to quickly see at which macro I'm looking so in the header of all my macro I add:
  [h:'<!-- ------------------------------------MACRO NAME ---------------------------------------->']

and sometimes I also add a

  [h:'<!-- ------------------------------------/END MACRO NAME ---------------------------------------->']

at the bottom, e.g. for the pause function!

  • If you're running heavy macro, especially ones with lots of loops then you will notice that the code runs a lot faster when the console is minimized. Keep this in mind!
  • In windows you can change the console settings. Especially for the MT log this is very usefull as the default console settings are width: 80 characters and Height: 300 lines. This means that lines are likely wrapped making them hard to read and with a history of 300 lines you won't come far. You can change this by right clicking on the top bar of the console, a context menu should pop-up with 'properties'. Here you go to the 'layout' tab and you can edit the 'Screen Buffer Size'. My settings are Width:600 and Height:2000. Ffortunately the settings are remembered by windows so you only need to do this once

Broadcast

broadcast() is a fairly new function to MT and is great for debugging purposes. The advantage of broadcast() is that it ports the result to the chat IMMEDIATELY. Usually all tekst to chat whether its 'this text' or [r:"this text"] will be accumulated until all macros are done and THEN the text is ported to the chatbox. So in case of an [abort] or [assert] or a crash in the code you will find either the assertion message, a bug report or nothing at all. All the accumulated text is discarded.

Two useful useages for broadcast():

Using broadcast to track down a code crash

lets say you have an macro of a few 100 lines, you run it and... nothing or some vague message like 'double : found'. If you want to pin point the crash you can simply put broadcast() lines between the code and see how far it gets. From the output you can deduce the location of the crash. Here an example, lets say you have:

 [a block of code]
 [another block of code]
 [and yet more blocks of code]
 [and finally a last block of code]

If you want to find out where the code stops:

 [a block of code]
 [h:broadcast("1")]
 [another block of code]
 [h:broadcast("2")]
 [and yet more blocks of code]
 [h:broadcast("3")]
 [and finally a last block of code]

If the output to the chat is eg:

 1
 2

Then you'll know that the error is somewhere inside [and yet more blocks of code].

Using broadcast to track variable development

I usually use pause() to check my variables, however if something goes wrong somewhere in a 500+ loop, you will be clicking 'ok' a lot. In these instances its much easier to add a

 [broadcast("variable_name: "+variable_name+"another_variable_name: "+another_variable_name)]

inside the loop. This way the code is not interrupted but you will get to see where the loop goes haywire.

Typical Bugs

Here I'll give a few examples of things that typically go wrong when coding, it useful to check this once in a while as a reminder and I hope that others will add to this list so this accumulates in a FOB (frequently occurring bugs)

My number one

can't

or better recognized in

<!-- this you can't do in MT script -->

This is not the most occuring bug, but it certainly is the most annoying as it REALLY screws up you're code and its hell to debug. The issue is with the single quote, when strategically placed this can result in an entire section of code not being executed, picking it up later or dropping back to the parent macro altogether. IF you also close the quote (that is put a second one in the comment as well) then there will be no issue, also if you encapsulate it in a [h:" "] (and not [h:' ']) it will run along nicely.

THE number one

It remains a guess but I think its a safe assumption that two : in one line of code (with the exception of switch and code) is the most commonly made mistake. Fortunately MT generates clear debug info on this one the syntax is ALWAYS:

[option , option , option : function]

';' occuring in the chatbox

I think this one is in second place, not a bug per se but annoying none the less. This occurs when you forget to include the false part in an if statement when using the code option e.g.

  [if(statement), CODE:{apparently the statement is true}]

will generate the following output

 apparently the statement is true
 ;

this is easily prevented by adding ;{} :

  [if(statement), CODE:{apparently the statement is true};{}]

--Wolph42 09:14, 7 June 2012 (UTC)

cheater you have been reported

This 'functionality' is embedded to prevent cheating...obviously, however this can also result in this error message (and only this error message) in your own code! This typically happens when broadcast() the result of an evalmacro() call, where the evalmacro result contains « guillemonts »: . E.g. paste this into your chat:

 [h:result = evalmacro(decode("4 The attack scoops out one of the target's eyes, inflicting [Fat=1d5] level(s) of Fatigue"))]
 [h:broadcast(result)]

To debug this I store 'result' in a lib:token property before I do the broadcast. From the text its usually easy to find where the guillemonts have entered. So:

 [h:result = evalmacro(decode("4 The attack scoops out one of the target's eyes, inflicting [Fat=1d5] level(s) of Fatigue"))]
 [h:setLibProperty("debugOutput", result, "lib:Token")]
 [h:broadcast(result)]

Then after running the macro I can copy paste that property inside a text editor and track down the guillemonts.