Assigning values to variables

How do I assign a timeline variable a value within a function? I tried declaring the variable on the main timeline:

  var dynamicHeight:Number;

then inside a function I write:

  dynamicHeight = (RootNode.childNodes.length)*160;

But when I write:
trace(dynamicHeight)

on the timeline I always get “Undefined”. But when I place the trace action inside the function where dynamicHeight is it comes back 1760 like it is suppose to.

I know the problem is scope, but why can’t I assign new values to a timeline variable from within a function or if/then statement?