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.
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 followingtypes 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.
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:
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 zeroy = 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:
“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.
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.
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:
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
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
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.