BrightSign BrightScript 2 Reference Guide

BrightScript 2
Reference
Jan 9, 2009
Minor updates: April 22, 2010
1
Table of Contents
INTRODUCTION .................................................................................................. 5
STATEMENT SUMMARY .................................................................................... 6
EXPRESSIONS, VARIABLES, AND TYPES ....................................................... 7
IDENTIFIERS ................................................................................................................................... 7
TYPES ............................................................................................................................................ 7
LITERALS (CONSTANTS) .................................................................................................................. 8
TYPE DECLARATION CHARACTERS ................................................................................................ 10
TYPE CONVERSION (PROMOTION) ................................................................................................. 10
EFFECTS OF TYPE CONVERSIONS ON ACCURACY .......................................................................... 10
OPERATORS ................................................................................................................................. 11
STRING OPERATORS .................................................................................................................... 11
FUNCTION REFERENCES ............................................................................................................... 11
LOGICAL AND BITWISE OPERATORS .............................................................................................. 11
DOTOPERATOR ......................................................................................................................... 12
ARRAY/FUNCTION CALL OPERATOR .............................................................................................. 12
= OPERATOR ................................................................................................................................ 13
ROKU OBJECTS, INTERFACES, AND LANGUAGE INTEGRATION .............. 14
A BRIEF SUMMARY OF ROKU OBJECTS .......................................................................................... 14
BRIGHTSCRIPT STATEMENTS THAT WORK WITH ROKU OBJECT INTERFACES .................................... 14
WRAPPER OBJECTS AND INTRINSIC TYPE PROMOTION .................................................................... 15
BRIGHTSCRIPT XML SUPPORT ..................................................................................................... 16
GARBAGE COLLECTION ................................................................................. 19
EVENTS ............................................................................................................. 20
THREADING MODEL ......................................................................................... 21
SCOPE ............................................................................................................... 22
CREATING AND USING INTRINSIC OBJECTS ............................................... 23
PROGRAM STATEMENTS ................................................................................ 24
DIM NAME (DIM1, DIM2, …, DIMK) ................................................................................................ 24
VARIABLE = EXPRESSION .............................................................................................................. 24
END ............................................................................................................................................ 25
STOP ......................................................................................................................................... 25
GOTO LABEL ............................................................................................................................... 25
RETURN EXPRESSION ................................................................................................................. 25
FOR COUNTER = EXP TO EXP STEP EXP NEXT COUNTER ........................................................... 25
FOR EACH ITEM IN OBJECT ......................................................................................................... 26
WHILE EXPRESSION / EXIT WHILE ................................................................................................. 27
REM ........................................................................................................................................... 27
IF EXPRESSION THEN STATEMENTS [ELSE STATEMENTS] ............................................................. 27
BLOCK IF, ELSEIF, THEN, ENDIF ............................................................................................. 27
PRINT [#OUTPUT_OBJECT], [@LOCATION], ITEM LIST ................................................................... 29
FUNCTION([PARAMETER AS TYPE, …]) AS TYPE / END FUNCTION ................................................... 30
2
Anonymous Functions .......................................................................................................................... 32
BUILT-IN FUNCTIONS ....................................................................................... 33
TYPE(VARIABLE) AS STRING .......................................................................................................... 33
RND(0) AS FLOAT
RND(RANGE AS INTEGER) AS INTEGER ......................................................................................... 33
BOX(X AS DYNAMIC) AS OBJECT .................................................................................................... 33
RUN(FILENAME AS STRING, OPTIONAL ARGS…) AS DYNAMIC ......................................................... 33
GETLASTRUNCOMPILEERROR() AS OBJECT .................................................................................. 34
GETLASTRUNRUNTIMEERROR() AS INTEGER ................................................................................ 34
........................................................................................................................... 34
GLOBAL FUNCTIONS ....................................................................................... 35
SLEEP(MILLISECONDS AS INTEGER) AS VOID ................................................................................. 35
WAIT (TIMEOUT AS INTEGER, PORT AS OBJECT) AS OBJECT........................................................... 35
CREATEOBJECT(NAME AS STRING) AS OBJECT ............................................................................. 35
GETINTERFACE(OBJECT AS OBJECT, IFNAME AS STRING) AS INTERFACE ........................................ 35
UPTIME(DUMMY AS INTEGER) AS FLOAT ....................................................................................... 36
REBOOTSYSTEM() AS VOID .......................................................................................................... 36
LISTDIR(PATH AS STRING) AS OBJECT .......................................................................................... 36
READASCIIFILE(FILEPATH AS STRING) AS STRING ......................................................................... 36
WRITEASCIIFILE(FILEPATH AS STRING, BUFFER AS STRING) AS BOOLEAN ...................................... 36
COPYFILE(SOURCE AS STRING, DESTINATION AS STRING) AS BOOL ............................................... 36
MATCHFILES(PATH AS STRING, PATTERN_IN AS STRING) AS OBJECT ............................................. 36
DELETEFILE(FILE AS STRING) AS BOOLEAN ................................................................................... 37
DELETEDIRECTORY(DIR AS STRING) AS BOOLEAN ......................................................................... 37
CREATEDIRECTORY(DIR AS STRING) AS BOOLEAN ........................................................................ 37
FORMATDRIVE(DRIVE AS STRING , FS_TYPE AS STRING) AS BOOLEAN ........................................... 37
GLOBAL STRING FUNCTIONS ....................................................................... 38
UCASE(S AS STRING) AS STRING ................................................................................................. 38
LCASE(S AS STRING) AS STRING .................................................................................................. 38
ASC (LETTER AS STRING) AS INTEGER .......................................................................................... 38
CHR (CH AS INTEGER) AS STRING ............................................................................................... 38
INSTR(POSITION TO START AS INTEGER, TEXT-TO-SEARCH AS STRING, SUBSTRING-TO-FIND AS
STRING) AS INTEGER .................................................................................................................... 38
LEFT (S AS STRING, N AS INTEGER) AS STRING ............................................................................ 38
LEN (S AS STRING) AS INTEGER .................................................................................................... 38
MID (S AS STRING, P AS INTEGER, [N AS INTEGER]) AS STRING ..................................................... 39
RIGHT (S AS STRING, N AS INTEGER) AS STRING .......................................................................... 39
STR (VALUE AS FLOAT) AS STRING
STRI(VALUE AS INTEGER) AS STRING ............................................................................................ 39
STRING (N AS INTEGER, CHARACTER AS STRING ) AS STRING
STRINGI (N AS INTEGER, CHARACTER AS INTEGER) AS STRING ....................................................... 39
VAL (S AS STRING) AS FLOAT ....................................................................................................... 39
GLOBAL MATH FUNCTIONS ........................................................................... 40
ABS (X AS FLOAT) AS FLOAT ........................................................................................................ 40
ATN (X AS FLOAT) AS FLOAT ........................................................................................................ 40
COS (X AS FLOAT) AS FLOAT ....................................................................................................... 40
CSNG (X AS INTEGER) AS FLOAT .................................................................................................. 40
CDBL(X AS INTEGER) AS FLOAT .................................................................................................... 40
EXP (X AS FLOAT) AS FLOAT ........................................................................................................ 40
FIX (X AS FLOAT) AS INTEGER ...................................................................................................... 40
3
INT(X AS FLOAT) AS INTEGER ....................................................................................................... 40
LOG(X AS FLOAT) AS FLOAT ........................................................................................................ 40
SGN(X AS FLOAT) AS INTEGER
SGN(X AS INTEGER) AS INTEGER .................................................................................................. 41
SIN(X AS FLOAT) AS FLOAT .......................................................................................................... 41
SQR(X AS FLOAT) AS FLOAT ........................................................................................................ 41
TAN(X AS FLOAT) AS FLOAT ......................................................................................................... 41
CORE ROKU OBJECTS .................................................................................... 42
IFLIST .......................................................................................................................................... 42
IFENUM ........................................................................................................................................ 42
IFMESSAGEPORT.......................................................................................................................... 42
ROINT, ROFLOAT, ROSTRING, ROBOOLEAN, ROBRSUB, ROINVALID ................................................. 43
ifInt ....................................................................................................................................................... 43
ifFloat ................................................................................................................................................. 43
ifString ................................................................................................................................................. 43
ifStringOps ........................................................................................................................................... 43
ifBrSub ................................................................ ................................................................ ................. 43
ifBoolean .............................................................................................................................................. 43
ROASSOCIATIVEARRAY ................................................................................................................. 44
ROARRAY ..................................................................................................................................... 45
ROBYTEARRAY ............................................................................................................................. 47
ROXMLELEMENT .......................................................................................................................... 48
ROXMLLIST ................................................................................................................................. 50
APPENDIX – PLANNED IMPROVEMENTS ................................ ...................... 52
APPENDIX – BRIGHTSCRIPT VERSIONS ....................................................... 53
APPENDIX – EXAMPLE SCRIPT - SNAKE ...................................................... 54
RESERVED WORDS ......................................................................................... 59
4
Introduction
Roku BrightScript is a powerful scripting language that makes it easy and quick to build media and networked applications for embedded devices. The language has integrated support for Roku Objects, a library of lightweight components. The APIs of the platform (device) the BrightScript is running on are all exposed to BrightScript as Roku Objects.
This document specifies the syntax of the language. To write useful applications, you should also refer to the Roku Object Reference Manual for the device you are targeting code for. This manual is designed for people that have some experience programming software. It is a reference guide, not a tutorial.
BrightScript compiles code into bytecode that is run by an interpreter. This compilation step happens every time a script is loaded and run. There is no separate compile step that results in a binary file being saved. In this way it is similar to JavaScript.
BrightScript statement syntax is not C-like; in this way it is similar to Python or Basic or Ruby. BrightScript Objects and named entry data structures are Associative Arrays; in this way it is similar to JavaScript or Lua. BrightScript supports dynamic typing (like
JavaScript), or declared types (like C or Java). BrightScript uses “interfaces” and
“components” for its APIs; similar to “.Net” or Java.
BrightScript is a powerful bytecode interpreted scripting language optimized for embedded devices; in this way it is unique. For example, BrightScript and the Roku Object architecture are written in 100% C for speed, efficiency, and portability.
BrightScript makes extensive use of the “integer” type (since many embedded processors don‟t have floating point units). This is different from languages like JavaScript where a
number is always a float. BrightScript numbers are only floats when necessary.
If you want to get a quick flavor of BrightScript code, see the Appendix of this manual
for the game “snake”.
BrightScript is optimized to be the “glue” that connects underling components for
network connectivity, media playback, and UI screens into user friendly applications with minimal programmer effort.
5
Statement Summary
BrightScript supports the following familiar looking statement types:
If / Then / Else If / Else / End If For / To / Next / Step / Exit For For Each / In / Next / Exit For While / End While / Exit While Function / End Function / As / Return Sub / End Sub Print Rem (or „) Goto Dim End Stop
BrightScript is not case sensitive.
Each statement‟s syntax is documented precisely later in the manual.
Here is an example:
Function Main() As Void
dim cavemen[10]
cavemen.push("fred") cavemen.push("barney") cavemen.push("wilma") cavemen.push("betty")
for each caveman in cavemen print caveman next
End Function
Each line may contain a single statement, or a colon (:) may be used to separate multiple statements on a single line.
myname = “fred” if myname=”fred” then yourname = “barney”:print yourname
6
Expressions, Variables, and Types
Identifiers
Identifiers (names of variables, functions, labels, or object member functions or interfaces (appear after a “.”)) have the following rules.
must start with an alphabetic character (a – z) may consist of alphabetic characters, numbers, or the symbol “_” (underscore) are not case sensitive may be of any length may not use a “reserved word” as the name (see appendix for list of reserved
words).
if a variable: may end with an optional type designator character ($ for string, %
for integer, ! for float, # for double) (functions do not support this).
For example:
a boy5 super_man$
Types
BrightScript uses dynamic typing. This means that every value also has a type determined at run time. However, BrightScript also supports declared types. This means that a variable can be made to always contain a value of a specific type. If a value is assigned to a variable (which has a specific type), the type of the value assigned will be converted to the variables type, if possible. If not possible, a runtime error will result.
The following types are supported in BrightScript:
Boolean – either true or false Integer– 32 bit signed integer number Float – the smallest floating point number format supported by the hardware or
software
Double - the largest floating point number format supported by the hardware or
software. Note that although BrightScript supports Double, Roku Objects do not.
String. – a sequence of ASCII characters. Currently strings are ASCII, not UTF-
8.
Object – a reference to a Roku Object (native component). Note that if you use
the “type()” function, you will not get “rotOBJECT”. Instead you will get the type of object. E.g.: “roList”, “roVideoPlayer”, etc. Also note that there is no
special type for “intrinsic” BrightScript objects. BrightScript objects are all built on the Roku Object type “roAssociatiaveArray”.
Interface- An interface in a Roku Object. If a “dot operator” is used on an
interface type, the member must be static (since there is no object context).
Invalid – the type invalid has only one value invalid. It is returned in various
cases, for example, when indexing an array that has never been set.
7
Dynamic typing – Unless otherwise specified, a variable is dynamically typed.
This means that the type is determined by the value assigned to it at evaluation
time. For example “1” is an int, “2.3” is a float, “hello” is a string, etc. A
variable that does not end in a type specifier character is dynamically typed. It will take on the type of the expression assigned to it, and may change its type.
For example: a=4 creates a as integer, then a = “hello”, changes the variable a to
a string.
Here are some examples of types. ? is a short cut for the “print” statement. The “type()”
function returns a string that identifies the type of the expression passed in.
BrightScript Micro Debugger. Enter any BrightScript statement, debug commands, or HELP.
BrightScript> ?type(1) Integer
BrightScript> ?type(1.0) Float
BrightScript> ?type("hello") String
BrightScript> ?type(CreateObject("roList")) roList
BrightScript> ?type(1%) Integer
BrightScript> b!=1 BrightScript> ?type(b!) Float
BrightScript> c$="hello" BrightScript> ?type(c$) String
BrightScript> d="hello again" BrightScript> ?type(d) String
BrightScript> d=1 BrightScript> ?type(d) Integer
BrightScript> d=1.0 BrightScript> ?type(d) Float
Literals (Constants)
Type Boolean: true, false
8
Type Invalid: invalid Type String: String in quotes, eg “this is a string” Type Integer: Hex integer, eg. &HFF, or decimal integer, eg. 255 Type Float: e.g., 2.01 or 1.23456E+30 or 2! Type Double: eg, 1.23456789D-12, or .2.3# Type BrSub , eg: MyFunction Type Integer: LINE_NUM – the current source line number.
The following rules determine how integers, doubles, and floats are determined:
1. If a constant contains 10 or more digits, or if D is used in the exponent, that
number is double precision. Adding a # declaration character also forces a constant to be double precision.
2. If the number is not double-precision, and if it contains a decimal point, then the
number is float. If the number is expressed in exponential notation with E preceding the exponent, the number is float.
3. If neither of the above is true of the constant, then it is an integer.
Array “literal”
The Array Operator [ ] can be used to declare an array. It may contain literals (constants), or expressions. E.g:
Myarray = [] Myarray = [ 1, 2, 3] Myarray = [ x+5, true, 1<>2, [“a”,”b”]]
Associative Array Literal
The { } operator can be used to define an Associative Array. It can contain literals or expressions. E.g:
aa={ } aa={key1:”value”, key2: 55, key3: 5+3 }
Both Arrays and Associative Arrays can also have this form:
aa = { Myfunc1: aFunction Myval1 : “the value” }
Note on Invalid vs. Object
Certain functions that return objects can also return invalid (for example, in the case when there is no object to return). In which case, the variable accepting the result must be dynamic, since it may get “invalid” or it may get an “object”.
l=[] a$=l.pop()
9
This example will return a type mismatch (a$ is a string, and can not contain “invalid”).
Character
Type
Examples
$
String
A$, ZZ$
%
Integer
A1%, SUM%
!
Single-Precision (float)
B!, N1!
#
Double-Precision (double)
A#, 1/3#, 2#
Many functions that return objects can return invalid as well
Type Declaration Characters
A type declaration character may be used at the end of a variable or literal to fix its type. Variables with the same identifier but separate types are separate variables. For example, a, a$, and a% are all independent.
Type Conversion (Promotion)
When operations are performed on one or two numbers, the result must be typed as integer, double or single-precision (float). When a +, -, or * operation is performed, the result will have the same degree of precision as the most precise operand. For example, if one operand is integer, and the other double-precision, the result will be double precision. Only when both operands are integers will a result be integer. If the result of an integer *,
-, or + operation is outside the integer range, the operation will be done in double precision and the result will be double precision.
Division follows the same rules as +, * and -, except that it is never done at the integer level: when both operators are integers, the operation is done as float with a float result . During a compare operation (< , >,=,etc.) the operands are converted to the same type before they are compared. The less precise type will always be converted to the more precise type.
The logical operators AND, OR and NOT first convert their operands to Boolean. The result of a logical operation is always a Boolean.
Effects of Type Conversions on Accuracy
When a number is converted to integer type, it is "rounded down"; i.e., the largest integer, which is not greater than the number is used. (This is the same thing that happens when the INT function is applied to the number.)
When a number is converted from double to single precision, it is "4/5 rounded" (the least significant digit is rounded up if the fractional part > =5. Otherwise, it is left unchanged).
10
When a single precision number is converted to double precision, only the seven most
( ) Function call, or Parentheses
. , [] Array Operator
^ (Exponentiation)
–, + (Negation)
*, /
+, -
<, >, = , <>, <=, >=
NOT
AND
OR
significant digits will be accurate.
Operators
Operations in the innermost level of parentheses are performed first, then evaluation proceeds according to the precedence in the following table. Operations on the same precedence are right-to-left associative, except for exponentiation, which is right-to-left.
String Operators
The following operators work with strings <. >, =, <>, <=, >=, +
Function References
= , <> work on variables that contain function references and function literals
Logical and Bitwise Operators
Example:
if a=c and not(b>40) then print “success”
AND, OR and NOT can be used for logical (Boolean) or bit manipulation & bitwise comparisons. If the arguments to these operators are Boolean, then they perform a logical operation. If the arguments are numeric, they perform bitwise operations.
x = 1 and 2 „ x is zero y = true and false „ y is false
11
When AND and OR are used for logical operations, only the necessary amount of the expression is executed. For example:
print true or invalid
The above statement will print “true”, where as:
print false or invalid
Will cause a runtime error because “invalid” is not a valid expression.
“dot” Operator
The “.” Operator can be used on any Roku Object or any AssociativeArray. It also has special meaning when used on roXMLElement or roXMLList. When used on a Roku Object, it refers to an interface or a member function. For example:
i=CreateObject(“roInt”) i.ifInt.SetInt(5) i.SetInt(5)
“ifInt” is the interface, and “SetInt” is the member function. Every member function of a
Roku Object is part of an interface. However, specifying the interface with the dot operator is optional. If it is left out, as in the last line of the example above, each interface in the object is searched for the member function. If there is a conflict (a member function with the same name appearing in two interfaces), then the interface should be specified.
When the “.” Operator is used on an Associative Array, it is the same as calling the Lookup() or AddReplace() member of the AssociativeArray Object.
aa=CreateObject(“roAssociativeArray”) aa.newkey=”the value”
print aa.newkey
The “.” Operator‟s parameters are set at compile time – they are not dynamic (unlike the Lookup() or AddReplace() functons).
See the section on XML support for details on using the dot operator on xml objects.
Array/Function Call Operator
The “[ ]” operator is used to access an Array (any Roku Object that has an “ifArray” interface, such as roArray). It can also be used to access an AssociativeArray.
The function call operator “( )” can be used to call a function. When used on a Function
literal (or variable containing a function reference), it calls the Function.
12
Examples:
aa=CreateObject(“roAssociativeArray”) aa[“newkey”]=”the value” print aa[“newkey”]
array=CreateObject(“roArray”, 10, true) array[2]=”two”
print array[2]
fivevar=five print fivevar()
array[1]=fivevar print array[1]() „ print 5
function five() As Integer return 5 end function
The “[ ]” operator takes expressions that are evaluated at runtime and so is different that a
“.” Operator in this way. The dot operator takes compile time identifiers.
Arrays in BrightScript are one dimension. Multi-dimension arrays are implemented as
arrays of arrays. The “[ ]” operator will automatically map “multi-dimensionality”. IE, the following two expressions to fetch “item” are the same:
dim array[5,5,5] item = array[1][2][3] item = array[1,2,3]
(**NOTE: if a multi-dimension array grows beyond its hint size the new entries are not automatically set to roArray**)
= Operator
“=” is used for both assignment and comparison. Example:
a=5 If a=5 then print “a is 5”
BrightScript does not support the use of the “=”Assignment operator inside an expression (like C does). This is to eliminate the common class of bugs where a programmer meant “comparison”, not “assignment”.
When an assignment occurs, intrinsic types are copied, but Roku Objects are reference counted.
13
Roku Objects, Interfaces, and Language Integration
[note: the name of Roku Objects will change to BrightScript Components]
The Roku Object architecture and library are separate from BrightScript, but BrightScript requires them.
All APIs exposed to BrightScript are exposed as Roku Objects. In other words, if
a platform wants to expose APIs to be scripted, the platform must register a new Roku Object. The Roku Object will most likely be written in C or C++.
BrightScript has language features that are designed to work with Roku Object
Interfaces. These include: for each, print, the array operator, and intrinsic objects.
Fundamental BrightScript building blocks are implemented as Roku Objects. For
example: Lists, Vector Arrays, Associative Arrays, and Objects.
A Brief Summary of Roku Objects
Roku Objects are light weight components that are implemented in C (or a C compatible language such as C++). C++ templates exist to help C++ programmers implement the key C functions needed to implement a Roku Object.
Roku Objects can be used in BrightScript, and they can be used by a C compatible language.
Roku Objects are robust against version changes. In other words, scripts are generally backwards compatible with Objects that have undergone version improvements.
Roku Objects keep a reference count and delete themselves when the reference count goes to zero.
A key Roku Object concept is the Interface. The term Interface is used here as it is in Java or Microsoft COM. An interface is a known set of member functions that implement a set of logic. In some ways an Interface is like a virtual base class in C++. Any script or C-compatible program can use an object‟s interface without regard to what type of object it is a part of, as long as it is familiar with a particular interface.
For example, the standard BrightScript serial interface (RS-232) object implements three
interfaces: “ifSerialControl”, “ifStreamReceive”, and “ifStreamSend”. Since the BrightScript “print” statement sends its output to any object that has an “ifStreamSend”
interface, it works with the serial object (and others).
BrightScript statements that work with Roku Object Interfaces
For each
14
The for-each statement works on any object that has an “ifEnum” interface. These include: Array, Associative Array, List, and Message Port.
Print
The print #object, “hello” format will print “into” any object that has an “ifStreamSend” interface. These include the TextField and SerialPort objects.
If the expression being printed evaluates to an object that has an “ifEnum” interface, print will print every item that can be enumerated.
In addition to printing the values of intrinsic types, “print” will also print any object that
exposes one of these interfaces: ifString, ifInt, ifFloat..
Wait
The wait function will work on any object that has an “ifMessagePort” interface.
Array Operator –“[]”
The array operator works on any object that has an “ifArray” or “ifAssociativeArray”
interface. This includes Array, Associative Array, and Lists.
Member access operator “.”
The “.” Operator works on any object that has an “ifAssociativeArray” interface (as well
as on any Roku Object (when calling a member function)). It also has special meaning when used on roXMLElement or roXMLList.
Expression Parsing
Any expression that is expecting an Integer, Float, Double, Boolean or String, can take an object with the “ifInt”, “ifFloat”, “ifBoolean” or “ifString” interface.
Wrapper Objects and intrinsic type promotion
The intrinsic BrightScript types integer, float, double, string, invalid, boolean and function all have object equivalents. If one of these intrinsic types is passed to a function that expects an Object, the appropriate wrapper object will be created, assigned the correct value, and passed to the function. This is sometimes referred to as “autoboxing”. This is how, for example, roArray can store integers and strings as well as objects.
Any expression that expects one of the above types will work with the corresponding wrapper object as well.
For example:
Dim array[10] Array.push(5) intobj = array.pop() print intobj+2 „ prints 7 print intobj.GetInt()+2 „ prints 7 print type(intobj) „ prints “roInt”
15
BrightScript XML Support
BrightScript supports XML via two Roku Objects, and some dedicated language features. The Roku Object roXMLElement provides support for parsing, generating, and containing XML. In addition, the roXMLList object is often used to hold lists of roXMLElement, and implements the BrightScript standard ifList interface as well as the ifXMLList interface. Language features are provided via the dot operator, and the @ operator.
Dot Operator on XML
1. When applied to an roXMLElement, the dot operator returns an roXMLList of
children that match the dot operand. If no tags match, an empty list is returned
2. When applied to an roXMLList, the dot operator aggregates the results of
performing the dot operator on each roXMLElement in the list.
Attribute Operator
The @ operator can be used on an roXMLElement to return a named attribute. When used on an roXMLList, the @ operator will return a value only if the list contains exactly one element.
For example, if the file “example.xml” contains the following:
<?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok">
<photos page="1" pages="5" perpage="100" total="500"> <photo id="3131875696" owner="21963906@N06" secret="f248c84625"
server="3125" farm="4" title="VNY 16R" ispublic="1" isfriend="0" isfamily="0" />
<photo id="3131137552" owner="8979045@N07" secret="b22cfde7c4"
server="3078" farm="4" title="hoot" ispublic="1" isfriend="0" isfamily="0" />
<photo id="3131040291" owner="27651538@N06" secret="ae25ff3942"
server="3286" farm="4" title="172 • 365 :: Someone once told me..." ispublic="1" isfriend="0"
</photos>
</rsp>
Then
rsp=CreateObject(“roXMLElement”) rsp.Parse(ReadAsciiFile(“example.xml”))
? rsp.photos.photo
Will return an roXMLList with three entries.
? rsp.photos.photo[0]
16
Will return an roXMLElement reference to the first photo (id="3131875696”).
? rsp.photos
Will return an roXMLList reference containing the photos tag.
rsp.photos@perpage
Will return the string 100.
Use the Text() method to return an element‟s text.
For example, if the variable booklist contains this roXMLElement:
<booklist> <book lang=eng>The Dawn of Man</book> </booklist>
Print booklist.book.gettext()
Will print “The Dawn of Man”.
print booklist.book@lang
Will print “eng”.
example flikr code clip
REM REM Interestingness REM pass an (optional) page of value 1 - 5 to get 100 photos REM starting at 0/100/200/300/400 REM REM returns a list of "Interestingness" photos with 100 entries REM
Function GetInterestingnessPhotoList(http as Object, page=1 As Integer) As Object
print "page=";page
http.SetUrl("http://api.flickr.com/services/rest/?method=flickr.interestingness .getList&api_key=YOURKEYGOESHERE&page="+mid(stri(page),2))
xml=http.GetToString()
rsp=CreateObject("roXMLElement") if not rsp.Parse(xml) then stop
return helperPhotoListFromXML(http, rsp.photos.photo) 'rsp.GetBody().Peek().GetBody())
End Function
Function helperPhotoListFromXML(http As Object, xmllist As Object,
17
owner=invalid As dynamic) As Object
photolist=CreateObject("roList") for each photo in xmllist photolist.Push(newPhotoFromXML(http, photo, owner)) next return photolist
End Function
REM REM newPhotoFromXML REM REM Takes an roXMLElement Object that is an <photo> ... </photo> REM Returns an brs object of type Photo REM photo.GetTitle() REM photo.GetID() REM photo.GetURL() REM photo.GetOwner() REM
Function newPhotoFromXML(http As Object, xml As Object, owner As dynamic) As Object photo = CreateObject("roAssociativeArray") photo.http=http photo.xml=xml photo.owner=owner photo.GetTitle=function():return m.xml@title:end function photo.GetID=function():return m.xml@id:end function photo.GetOwner=pGetOwner photo.GetURL=pGetURL return photo End Function
Function pGetOwner() As String if m.owner<>invalid return m.owner return m.xml@owner End Function
Function pGetURL() As String a=m.xml.GetAttributes() url="http://farm"+a.farm+".static.flickr.com/"+a.server+"/"+a.id+"_"+a.se cret+".jpg" return url End Function
18
Loading...
+ 41 hidden pages