quarta-feira, 6 de agosto de 2008

Xecute Scoping

A nasty gotcha in scoping when you try to use Caché's "interpret a string containing code" command xecute inside an object.

You can execute (ie. eval) a string containing a piece of Caché ObjectScript with xecute like this :


set m = "write 2+2"
xecute m


xecute only works on statements, not expressions. But you can use the alternative @ for that. Eg.


set m = "2+2"
write @m



However, if you try to use this inside a class definition, something odd happens.

When a class is compiled, the string which contains code is obviously not affected by the pre-processor. But it seems that when the method is run and the string xecuted, the variable names in the string don't get bound to the scope within the method. Instead they get their values from the global frame or somewhere else entirely.

Look at the following example.

A class :


Class MY.ScopeGotcha Extends %Persistent [ ClassType = persistent, ProcedureBlock ]
{

Method f() {
set x = 6
set m = "write !,x"
xecute m
}

}


Now try running it from the terminal like this :


set x = 9
set y = ##class(MY.ScopeGotcha).%New()
do y.f()


Guess what it prints ... :-)

Nenhum comentário: