Tuesday, March 20, 2012

Changes to the String type in EDT .8

In EDT .8, the String type has been changed from a Value type to a Reference type.  (More information on Value types and Reference types can be found on the EDT Language Overview Wiki page) .  In general, this change will not have an impact on existing EGL code, but it is possible for existing functions to behave differently at runtime if they specify a parameter of type String, and do not specify an explicit modifier (i.e. 'in', 'inout', etc).

In EDT, the default modifier for a Value type function parameter is 'inout', which means that the original value is passed to the function parameter, instead of a copy, and any changes made to the parameter in the function will be visible to the caller of the function.  For example:


function func1()
  var1 int = 2;  // int is a Value type
  addOneFunction(var1); 
  // var1 is now 3
end

function addOneFunction(param1 int)
  param1 += 1;  // Add one to param1
end


In EDT, the default modifier for a Reference type function parameter is 'in', which means that a copy of the value is passed to the function parameter, and any changes made to the parameter in the function will not be visible to the caller of the function.  For example:


function func1()
  var1 Decimal = 2; // decimal is a Reference type
  doNotAddOneFunction(var1); 
  // var1 is still 2
end

function doNotAddOneFunction(param1 Decimal)
  param1 += 1;  // Add one to param1
end


Now that Strings are Reference types in EDT, code that used to rely on the default behavior of the 'addOneFunction' will produce different results, similar to the 'doNotAddOneFunction' function, if an explicit modifier is not specified.  For example:


function func1()
  var1 String;
  modifyString(var1); 
  // In EDT .7, var1 would be "Modified String"
  // In EDT .8, var1 will now be ""
end

function modifyString(param1 String)
  param1 += "Modified String";
end


To resolve these issues, you can add an explicit modifier to the function parameter:

function modifyString(param1 String inout)


Additional information on Reference types and Function Parameters
When a reference type is passed to a function parameter using the 'in' modifier, a copy is made by allocating new memory for the parameter that points to the same memory as the value being passed to the function.  If you assign the parameter a new value, only the memory allocated for the parameter is updated to point to the memory used by the new value. 

When a reference type is passed to a function parameter using the 'inout' modifier, the parameter essentially maps to the same memory as the value being passed into the parameter.  If you assign the parameter to a new value, the value passed into the function is updated as well, since the parameter represents the same memory as the original value.

-Brian

No comments:

Post a Comment

Post a Comment