|
Script package is a pnuts.ext.ScriptPackage object that is used in user's scripts as an hashtable. Script packages can be created by $ function, which is implemented by pnuts.ext.ScriptPackage.Function class.
# of parameters The types The action 1 java.lang.String Evaluate the string in a script package 1 java.lang.Object[] Interpret each element as a [key, value] pair and define them in a script package any any If there is any function in the parameters, register the function with its name in a script package.
e.g.
p = $( ) p.x = 1 p.y = 2 q = $("x = 1; y = 2") q.x ==> 1 q.y ==> 2 r = $([["a", "hello"], ["b", "world"]]) r.a ==> "hello" r.b ==> "world"
Unlike ordinary functions, $ evaluates its parameters with the caller's context. See also property() function.
When a function is specified as a parameter of $ function, the function is registered in the script package with its name, and can be called in method-call style.
e.g.
s = $(function hello () "hello", function bye () "bye") s.hello() ==> "hello" s.bye() ==> "bye"
Since pnuts.ext.ScriptPackage implements pnuts.lang.AbstractData interface, instance methods of pnuts.lang.Package class can not be called in Pnuts directrly. Instead, the following methods are provided.
e.g.
t = $() symbol = "%%%".intern() $.set(t, symbol, "value") // t.set(symbol, "value") $.get(t, symbol) // t.get(symbol) $.keys(t) // t.keys() $.save(t, open("test.ser", "w")) // t.save(open("test.ser", "w"))
With a script package, a kind of abstract data type can be defined.
e.g.
function Stack() $( function Cell(x){ this = $() this.object = x this }, cell = null, function pop(){ c = cell if (c == null) throw("underflow") cell = c.next c.object }, function push(x){ c = cell cell = Cell(x) cell.next = c null } ) s = Stack() s.push(100) s.pop()
Script packages, of cource, can be the current package.
e.g.
package(Stack()) push(100) pop()