"GandK-Geoff" wrote:
"jbrave" wrote:
One thing I see in your code and in TheEndless code is these constructions where it appears you are embedding a function call in an roAssociativeArray and giving them a label and then calling them as a method. I don't completely understand this- it seems like It adds an extra level of unreadability to the code but maybe allows you to simplify your code at the same time? Does this stuff execute faster or something?
He is not putting a function *call* in the roAssociativeArray ("AA" for short), he is putting a function *reference* into the AA. That is, in fact, the way that objects are created in BrightScript; a user-defined object is just an AA with some entries that are member variables and some entries that are methods (function references). ("Native" objects created with CreateObject() are actually C++ objects.)
BrightScript AA-based objects don't really have classes and inheritance in the classic OO style; they are in this sense somewhat weaker even than JavaScript's object system. Still, they support encapsulation, polymorphism, and namespace control (methods can be defined with inline anonymous function definitions, thus avoiding pollution of the top-level namespace). That's good enough to get a lot of useful work done.
The main benefit we use it for is encapsulation.
A classic (and my personal favorite) example is a coordinate system. Here's how we can use this to model points and use the points to model a line.
function newPoint() as object
point = {
x: 0
y: 0
setX: function(x as integer)
m.x = x
end function
setY: function(y as integer)
m.y = x
end function
set: function(x as integer, y as integer)
m.x = x
m.y = y
end function
toStr: function()
return "("+m.x.toStr()+","+m.y.toStr()+")";
end function
}
return point
end function
function newLine() as object
line = {
p1: invalid
p2: invalid
setStart: function(p as object)
m.p1 = p
end function
setEnd: function(p as object)
m.p2 = p
end function
toStr(): function()
return "line from "+m.p1.toStr()+" to "+m.p2.toStr()"
end function
}
return line
end function
point1 = newPoint()
point1.setX(2)
point1.setY(4)
print point1.toStr() ' prints "(2,4)"
point2 = newPoint()
point2.set(9,11)
print point2.toStr() ' prints "(9,11)"
otherpoint = newPoint()
' newPoint() just returns an associative array
otherpoint.x = 10
otherpoint.y = 20
print otherpoint.toStr() ' prints "(10,20)"
line1 = newLine()
line1.setStart(point1)
line1.setEnd(point2)
print line1.toStr() ' prints "line from (2,4) to (9,11)"
As you can see, each associative array is a self contained chunk of both data and methods to work on that data, or in CS parlance they are "objects."
P.S. The code above is a bit short on sanity checks to ensure the correct things are passed into the methods. Also, I'm a fan of returning
m from methods so I can chain them, like point.setX(1).setY(5).setZ(4).vectorize()
-- GandK Labs
Check out Reversi! in the channel store!