What to Script
Scripting can be used to interact with XML elements, or to create variables and functions for custom applications. It is important to note that scripting in qdex is essentially programming; while open-ended, it is easy to compromise document stability.
Call a Method
Methods are used to change the state of XML elements, and can include starting/stopping a simulation, resetting the axis range of a plot, or interacting with a button or toggle. Available methods can be found on the Scripting Reference page, and the Simulation Properties page.
The example below shows two ways to call a simulation Start() method from a button's onClick event.
<button content="Start Simulation"> <onClick> mySim:Start() </onClick> </button>
<button content="Start Simulation" onClick="mySim:Start()" />
Alter a Property
Properties define how an XML element appears or works. Some properties that can be changed are style properties (color, visibility, margins, etc), the value of a slider, or the text in a paragraph. Some properties are read only, meaning that you can retrieve their value, but cannot alter it.
It is important to note the type of value that a property is expecting to receive. For example, when assigning the value of a slider to a number taken from a textField, the value must first be converted from string to float using the Lua function tonumber().
In the example below, the Text property of a paragraph is updated each time the value of the slider changes.
<p name="myPar" /> <slider min="0" max="10"> <onValueChanged> myPar.Text = string.format("Value of slider: %0.1f", value) </onValueChanged> </slider>
The scripting engine that is included in the qdex framework is built on NLua which binds the Lua scripting language to .NET. Because of this, authors have the freedom to create code in their modules that go beyond altering XML elements. For more information on the basic structure and syntax of Lua check out the Reference Manual. Note that some elements of Lua are not accessible from qdex (e.g. I/O, print); post on the forum if you need clarification.
The below example combines all three scripting types into a simple kinematic equation solver.
- Custom variables and a function are defined to calculate the value of a kinematic equation.
- The function also updates the Text property of a paragraph.
- The onActivePageChanged event calls the simulation Start() method.
<script> local vi = 10; local a = 1; local function launch(t) d = vi*t + 0.5*a*t*t myLabel.Text = string.format("Distance = %0.2f", d) end </script> <p name="myLabel" /> <simulation name="distSim" onActivePageChanged="distSim:Start()" onUpdate="launch(time)" duration="10" />