User Tools

Site Tools


script:walkthrough:scopes

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
script:walkthrough:scopes [2017-03-13 18:13] skyjakescript:walkthrough:scopes [2019-11-25 08:55] (current) – [Importing modules] skyjake
Line 1: Line 1:
 +<- Functions ^ ^ Miscellaneous ->
 +
 +====== Scopes ======
 +
 +The following scopes (namespaces) are defined:
 +
 +  * Each module has its own global scope.
 +  * Each function has its own local scope.
 +  * In a class definition, the scope is the [[records#classes|class namespace]].
 +
 +===== Global assignment =====
 +
 +The global assignment '':='' operator inserts variables to the module's global namespace.
 +
 +  a = 1
 +  def globalAssign()
 +      a := 2
 +  end
 +  globalAssign()
 +  print a
 +
 +Output:
 +
 +  2
 +
 +===== Local namespace =====
 +
 +Built-in function ''locals()'' returns the local namespace as a record.
 +
 +  # script "test.ds"
 +  a = 'hello'; b = 'world'
 +  print locals()
 +
 +Output:
 +
 +  __file__:/src/test.ds
 +  a:       hello
 +  b:       world
 +
 +===== Importing modules =====
 +
 +The ''import'' keyword is used to import modules. All built-in modules and all script files on the [[fs:packages#scripting|import path]] are available for importing.
 +
 +  import App
 +
 +When a module is first imported, its global namespace is initialized by executing all statements in the module's global scope. All modules that then import the module will receive a reference to the same record.
 +
 +The import statement can also be used to make a copy instead of regular importing.
 +
 +  import record other
 +
 +This imports //other// (from a file called **other.ds** somewhere on the import path), makes an owned copy of the record, and assigns it to a local variable named //other//. It is equivalent to the following:
 +
 +  import other
 +  other = Record(other)
  
script/walkthrough/scopes.txt · Last modified: 2019-11-25 08:55 by skyjake