Lua Programming Language

Total Page:16

File Type:pdf, Size:1020Kb

Lua Programming Language Lua Programming Language An Introduction Dr. Christian Storm TNG Big Techday 7 23rd May 2014 About Lua ■ invented as configuration and data description language ■ first version released 1993, current version is 5.2.3 ■ Lua is interpreted, dynamically typed, garbage collected, has closures, coroutines, <insert fancy stuff here>, … ■ Lua is ■ clean & simple: a designed, not evolved language ■ fast: even faster with LuaJIT see, e.g., Computer Language Benchmarks Game, Hash benchmark ■ small: liblua.so.5.2.3 is 200K, 60 source files, 14,728 lines code (C,C++,make) ■ portable: written in ANSI C/C++ ■ embeddable & extensible: C/C++, Java, C#, Perl, Python, Ruby, … ■ Lua complements C’s low level power (e.g., via inline Assembler) I high(er) level language expressibility without having to use C++ :) Lua Programming Language – An Introduction 1 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I …scriptingalmostand and in may everywhereSnakeeven theCrytek’s other UITetris! subsystem places CryEngine-based in Adobe’s you of probably Blizzard’s Photoshop games, wouldn’t World Lightroom e.g., of expect WarcraftFarCry it … and Crysis Lua … so what? I empowers your Texas Instruments EK-LM3S to play Pong •◦◦◦◦◦◦ Lua Programming Language – An Introduction 2 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I empowersscriptingalmostand… and in may everywhereeven theCrytek’s your other UITetris! subsystem Texas places CryEngine-based in Adobe’s Instruments you of probably Blizzard’s Photoshop EK-LM3S games, wouldn’t World Lightroom e.g., to of expect play WarcraftFarCry Pong it … and Crysis Lua … so what? I … and Snake ••◦◦◦◦◦ Lua Programming Language – An Introduction 2 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I empowers…scriptingalmostand and in may everywhereSnake theCrytek’s your other UI subsystem Texas places CryEngine-based in Adobe’s Instruments you of probably Blizzard’s Photoshop EK-LM3S games, wouldn’t World Lightroom e.g., to of expect play WarcraftFarCry Pong it … and Crysis Lua … so what? I … and even Tetris! •••◦◦◦◦ Lua Programming Language – An Introduction 2 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I empowers…scriptingalmostand and in may everywhereSnakeeven Crytek’s your other Tetris! Texas places CryEngine-based in Adobe’s Instruments you probably Photoshop EK-LM3S games, wouldn’t Lightroom e.g., to expect play FarCry Pong it … and Crysis Lua … so what? I scripting the UI subsystem of Blizzard’s World of Warcraft ••••◦◦◦ Lua Programming Language – An Introduction 2 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I empowers…scriptingalmostand and in may everywhereSnakeeven the your other UITetris! subsystem Texas places in Adobe’s Instruments you of probably Blizzard’s Photoshop EK-LM3S wouldn’t World Lightroom to of expect play Warcraft Pong it … Lua … so what? I scripting Crytek’s CryEngine-based games, e.g., FarCry and Crysis •••••◦◦ Lua Programming Language – An Introduction 2 awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I empowers…scriptingand and in may Snakeeven theCrytek’s your other UITetris! subsystem Texas places CryEngine-based Instruments you of probably Blizzard’s EK-LM3S games, wouldn’t World e.g., to of expect play WarcraftFarCry Pong it … and Crysis Lua … so what? I almost everywhere in Adobe’s Photoshop Lightroom ••••••◦ Lua Programming Language – An Introduction 2 I empowers…scriptingalmost and everywhereSnakeeven theCrytek’s your UITetris! subsystem Texas CryEngine-based in Adobe’s Instruments of Blizzard’s Photoshop EK-LM3S games, World Lightroom e.g., to of play WarcraftFarCry Pong and Crysis Lua … so what? awesome X11 window manager vim editor VLC Media Player http://awesome.naquadah.org http://www.vim.org http://www.videolan.org/vlc/ LuaTEX Angry Birds Nginx HTTP Server http://www.luatex.org http://www.angrybirds.com http://nginx.org Wireshark NetBSD’s Kernel Havok Engine http://www.wireshark.org http://www.netbsd.org http://www.havok.com I and in may other places you probably wouldn’t expect it … ••••••• Lua Programming Language – An Introduction 2 Outline Lua Language Basics Syntax Data Types Statements and Control Structures Functions Closures More Advanced Lua Modules Coroutines Metatables and Metamethods OOP in Lua Lua Programming Language – An Introduction 3 Lua Language Basics – Syntax What does Lua look like? function factorial(n, ans) ans = ans and ans or 1 if ans == math.huge then print(”E: overflow”) return nil end if n ~= 0 then return factorial(n-1, n*ans) end return ans end fact = factorial(arg[1] and tonumber(arg[1]) or 0) print(fact) > lua propertailrecursionfactorial.lua 5 120 > _ Lua Programming Language – An Introduction 4 Lua Language Basics – Syntax Lua’s Syntax chunk ::= block block ::= {stat}[retstat] stat ::= ’;’ | varlist ’=’ explist | functioncall | label | break | goto Name | do block end | while exp do block end | repeat block until exp | if exp then block {elseif exp then block}[else block] end | for Name ’=’ exp ’,’ exp [’,’ exp] do block end | for namelist in explist do block end | function funcname funcbody | local function Name funcbody | local namelist [’=’ explist] retstat ::= return [explist] [’;’] label ::= ’::’ Name ’::’ funcname ::= Name {’.’ Name} [’:’ Name] varlist ::= var {’,’ var} var ::= Name | prefixexp ’[’ exp ’]’ | prefixexp ’.’ Name namelist ::= Name {’,’ Name} explist ::= exp {’,’ exp} exp ::= nil | false | true | Number | String | ’...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | ’(’ exp ’)’ functioncall ::= prefixexp args | prefixexp ’:’ Name args args ::= ’(’ [explist] ’)’ | tableconstructor | String functiondef ::= function funcbody funcbody ::= ’(’ [parlist] ’)’ block end parlist ::= namelist [’,’ ’...’] | ’...’ tableconstructor ::= ’{’ [fieldlist] ’}’ fieldlist ::= field {fieldsep field}[fieldsep] field ::= ’[’ exp ’]’ ’=’ exp | Name ’=’ exp | exp fieldsep ::= ’,’ | ’;’ binop ::= ’+’ | ’-’ | ’*’ | ’/’ | ’^’ | ’%’ | ’..’ | ’<’ | ’<=’ | ’>’ | ’>=’ | ’==’ | ’~=’ | and | or (**) unop ::= ’-’ | not | ’#’ (**) operator precedence is missing http://www.lua.org/manual/5.2/manual.html#9 Lua Programming Language – An Introduction 5 Lua Language Basics – Syntax … compared to Python 3.4’s Syntax single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE try_stmt: (’try’ ’:’ suite ((except_clause ’:’ suite)+ [’else’ ’:’ suite] file_input:(NEWLINE | stmt)* ENDMARKER [’finally’ ’:’ suite] | ’finally’ ’:’ suite)) eval_input: testlist NEWLINE* ENDMARKER with_stmt:’with’ with_item (’,’ with_item)* ’:’ suite decorator:’@’ dotted_name [ ’(’ [arglist] ’)’ ] NEWLINE with_item: test [’as’ expr] decorators: decorator+ except_clause:’except’[test [’as’ NAME]] decorated: decorators (classdef | funcdef) suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT funcdef:’def’ NAME parameters [’->’ test] ’:’ suite test: or_test [’if’ or_test ’else’ test] | lambdef parameters: ’(’ [typedargslist] ’)’ test_nocond: or_test | lambdef_nocond typedargslist:(tfpdef [’=’ test] (’,’ tfpdef [’=’ test])* [’,’ lambdef:’lambda’[varargslist] ’:’ test [’*’ [tfpdef] (’,’ tfpdef [’=’ test])* [’,’ ’**’ tfpdef] | ’**’ tfpdef]] lambdef_nocond:’lambda’[varargslist] ’:’ test_nocond | ’*’ [tfpdef] (’,’ tfpdef [’=’ test])* [’,’ ’**’ tfpdef] | ’**’ tfpdef) or_test: and_test (’or’ and_test)* tfpdef: NAME [’:’ test] and_test: not_test (’and’ not_test)* varargslist:(vfpdef [’=’ test] (’,’ vfpdef [’=’ test])* [’,’ not_test:’not’ not_test | comparison [’*’ [vfpdef] (’,’ vfpdef [’=’ test])* [’,’ ’**’ vfpdef] | ’**’ vfpdef]] comparison: expr (comp_op expr)* | ’*’ [vfpdef] (’,’ vfpdef [’=’ test])* [’,’ ’**’ vfpdef] | ’**’ vfpdef) comp_op: ’<’|’>’|’==’|’>=’|’<=’|’<>’|’!=’|’in’|’not’’in’|’is’|’is’’not’ vfpdef: NAME star_expr: ’*’ expr stmt: simple_stmt | compound_stmt expr: xor_expr (’|’ xor_expr)* simple_stmt: small_stmt
Recommended publications
  • Programming Languages
    Programming Languages Recitation Summer 2014 Recitation Leader • Joanna Gilberti • Email: [email protected] • Office: WWH, Room 328 • Web site: http://cims.nyu.edu/~jlg204/courses/PL/index.html Homework Submission Guidelines • Submit all homework to me via email (at [email protected] only) on the due date. • Email subject: “PL– homework #” (EXAMPLE: “PL – Homework 1”) • Use file naming convention on all attachments: “firstname_lastname_hw_#” (example: "joanna_gilberti_hw_1") • In the case multiple files are being submitted, package all files into a ZIP file, and name the ZIP file using the naming convention above. What’s Covered in Recitation • Homework Solutions • Questions on the homeworks • For additional questions on assignments, it is best to contact me via email. • I will hold office hours (time will be posted on the recitation Web site) • Run sample programs that demonstrate concepts covered in class Iterative Languages Scoping • Sample Languages • C: static-scoping • Perl: static and dynamic-scoping (use to be only dynamic scoping) • Both gcc (to run C programs), and perl (to run Perl programs) are installed on the cims servers • Must compile the C program with gcc, and then run the generated executable • Must include the path to the perl executable in the perl script Basic Scope Concepts in C • block scope (nested scope) • run scope_levels.c (sl) • ** block scope: set of statements enclosed in braces {}, and variables declared within a block has block scope and is active and accessible from its declaration to the end of the block
    [Show full text]
  • Armadillo C++ Library
    Armadillo: a template-based C++ library for linear algebra Conrad Sanderson and Ryan Curtin Abstract The C++ language is often used for implementing functionality that is performance and/or resource sensitive. While the standard C++ library provides many useful algorithms (such as sorting), in its current form it does not provide direct handling of linear algebra (matrix maths). Armadillo is an open source linear algebra library for the C++ language, aiming towards a good balance between speed and ease of use. Its high-level application programming interface (function syntax) is deliberately similar to the widely used Matlab and Octave languages [4], so that mathematical operations can be expressed in a familiar and natural manner. The library is useful for algorithm development directly in C++, or relatively quick conversion of research code into production environments. Armadillo provides efficient objects for vectors, matrices and cubes (third order tensors), as well as over 200 associated functions for manipulating data stored in the objects. Integer, floating point and complex numbers are supported, as well as dense and sparse storage formats. Various matrix factorisations are provided through integration with LAPACK [3], or one of its high performance drop-in replacements such as Intel MKL [6] or OpenBLAS [9]. It is also possible to use Armadillo in conjunction with NVBLAS to obtain GPU-accelerated matrix multiplication [7]. Armadillo is used as a base for other open source projects, such as MLPACK, a C++ library for machine learning and pattern recognition [2], and RcppArmadillo, a bridge between the R language and C++ in order to speed up computations [5].
    [Show full text]
  • Chapter 5 Names, Bindings, and Scopes
    Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 5.2 Names 199 5.3 Variables 200 5.4 The Concept of Binding 203 5.5 Scope 211 5.6 Scope and Lifetime 222 5.7 Referencing Environments 223 5.8 Named Constants 224 Summary • Review Questions • Problem Set • Programming Exercises 227 CMPS401 Class Notes (Chap05) Page 1 / 20 Dr. Kuo-pao Yang Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 Imperative languages are abstractions of von Neumann architecture – Memory: stores both instructions and data – Processor: provides operations for modifying the contents of memory Variables are characterized by a collection of properties or attributes – The most important of which is type, a fundamental concept in programming languages – To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 5.2 Names 199 5.2.1 Design issues The following are the primary design issues for names: – Maximum length? – Are names case sensitive? – Are special words reserved words or keywords? 5.2.2 Name Forms A name is a string of characters used to identify some entity in a program. Length – If too short, they cannot be connotative – Language examples: . FORTRAN I: maximum 6 . COBOL: maximum 30 . C99: no limit but only the first 63 are significant; also, external names are limited to a maximum of 31 . C# and Java: no limit, and all characters are significant . C++: no limit, but implementers often impose a length limitation because they do not want the symbol table in which identifiers are stored during compilation to be too large and also to simplify the maintenance of that table.
    [Show full text]
  • Introduction to Programming in Lisp
    Introduction to Programming in Lisp Supplementary handout for 4th Year AI lectures · D W Murray · Hilary 1991 1 Background There are two widely used languages for AI, viz. Lisp and Prolog. The latter is the language for Logic Programming, but much of the remainder of the work is programmed in Lisp. Lisp is the general language for AI because it allows us to manipulate symbols and ideas in a commonsense manner. Lisp is an acronym for List Processing, a reference to the basic syntax of the language and aim of the language. The earliest list processing language was in fact IPL developed in the mid 1950’s by Simon, Newell and Shaw. Lisp itself was conceived by John McCarthy and students in the late 1950’s for use in the newly-named field of artificial intelligence. It caught on quickly in MIT’s AI Project, was implemented on the IBM 704 and by 1962 to spread through other AI groups. AI is still the largest application area for the language, but the removal of many of the flaws of early versions of the language have resulted in its gaining somewhat wider acceptance. One snag with Lisp is that although it started out as a very pure language based on mathematic logic, practical pressures mean that it has grown. There were many dialects which threaten the unity of the language, but recently there was a concerted effort to develop a more standard Lisp, viz. Common Lisp. Other Lisps you may hear of are FranzLisp, MacLisp, InterLisp, Cambridge Lisp, Le Lisp, ... Some good things about Lisp are: • Lisp is an early example of an interpreted language (though it can be compiled).
    [Show full text]
  • Cygwin User's Guide
    Cygwin User’s Guide Cygwin User’s Guide ii Copyright © Cygwin authors Permission is granted to make and distribute verbatim copies of this documentation provided the copyright notice and this per- mission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this documentation under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this documentation into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. Cygwin User’s Guide iii Contents 1 Cygwin Overview 1 1.1 What is it? . .1 1.2 Quick Start Guide for those more experienced with Windows . .1 1.3 Quick Start Guide for those more experienced with UNIX . .1 1.4 Are the Cygwin tools free software? . .2 1.5 A brief history of the Cygwin project . .2 1.6 Highlights of Cygwin Functionality . .3 1.6.1 Introduction . .3 1.6.2 Permissions and Security . .3 1.6.3 File Access . .3 1.6.4 Text Mode vs. Binary Mode . .4 1.6.5 ANSI C Library . .4 1.6.6 Process Creation . .5 1.6.6.1 Problems with process creation . .5 1.6.7 Signals . .6 1.6.8 Sockets . .6 1.6.9 Select . .7 1.7 What’s new and what changed in Cygwin . .7 1.7.1 What’s new and what changed in 3.2 .
    [Show full text]
  • Scala Tutorial
    Scala Tutorial SCALA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Scala Tutorial Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates features of object-oriented and functional languages. This tutorial gives a great understanding on Scala. Audience This tutorial has been prepared for the beginners to help them understand programming Language Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels. Prerequisites Scala Programming is based on Java, so if you are aware of Java syntax, then it's pretty easy to learn Scala. Further if you do not have expertise in Java but you know any other programming language like C, C++ or Python, then it will also help in grasping Scala concepts very quickly. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] TUTORIALS POINT Simply Easy Learning Table of Content Scala Tutorial ..........................................................................
    [Show full text]
  • Automating Your Sync Testing
    APPLICATION NOTE By automating system verification and conformance testing to ITU-T synchronization standards, you’ll save on time and resources, and avoid potential test execution errors. This application note describes how you can use the Paragon-X’s Script Recorder to easily record Tcl, PERL and Python commands that can be integrated into your own test scripts for fast and efficient automated testing. AUTOMATING YOUR SYNC TESTING calnexsol.com Easily automate synchronization testing using the Paragon-X Fast and easy automation by Supports the key test languages Pre-prepared G.8262 Conformance recording GUI key presses Tcl, PERL and Python Scripts reduces test execution errors <Tcl> <PERL> <python> If you perform System Verification language you want to record i.e. Tcl, PERL SyncE CONFORMANCE TEST and Conformance Testing to ITU-T or Python, then select Start. synchronization standards on a regular Calnex provides Conformance Test Scripts basis, you’ll know that manual operation to ITU-T G.8262 for SyncE conformance of these tests can be time consuming, testing using the Paragon-X. These tedious and prone to operator error — as test scripts can also be easily tailored well as tying up much needed resources. and edited to meet your exact test Automation is the answer but very often requirements. This provides an easy means a lack of time and resource means it of getting your test automation up and remains on the ‘To do’ list. Now, with running and providing a repeatable means Calnex’s new Script Recorder feature, you of proving performance, primarily for ITU-T can get your automation up and running standards conformance.
    [Show full text]
  • Building Performance Measurement Tools for the MINIX 3 Operating System
    Building Performance Measurement Tools for the MINIX 3 Operating System Rogier Meurs August 2006 Contents 1 INTRODUCTION 1 1.1 Measuring Performance 1 1.2 MINIX 3 2 2 STATISTICAL PROFILING 3 2.1 Introduction 3 2.2 In Search of a Timer 3 2.2.1 i8259 Timers 3 2.2.2 CMOS Real-Time Clock 3 2.3 High-level Description 4 2.4 Work Done in User-Space 5 2.4.1 The SPROFILE System Call 5 2.5 Work Done in Kernel-Space 5 2.5.1 The SPROF Kernel Call 5 2.5.2 Profiling using the CMOS Timer Interrupt 6 2.6 Work Done at the Application Level 7 2.6.1 Control Tool: profile 7 2.6.2 Analyzing Tool: sprofalyze.pl 7 2.7 What Can and What Cannot be Profiled 8 2.8 Profiling Results 8 2.8.1 High Scoring IPC Functions 8 2.8.2 Interrupt Delay 9 2.8.3 Profiling Runs on Simulator and Other CPU Models 12 2.9 Side-effect of Using the CMOS Clock 12 3 CALL PROFILING 13 3.1 Introduction 13 3.1.1 Compiler-supported Call Profiling 13 3.1.2 Call Paths, Call and Cycle Attribution 13 3.2 High-level Description 14 3.3 Work Done in User-Space 15 3.3.1 The CPROFILE System Call 15 3.4 Work Done in Kernel-Space 16 3.4.1 The PROFBUF and CPROF Kernel Calls 16 3.5 Work Done in Libraries 17 3.5.1 Profiling Using Library Functions 17 3.5.2 The Procentry Library Function 17 3.5.3 The Procexit Library Function 20 3.5.4 The Call Path String 22 3.5.5 Testing Overhead Elimination 23 3.6 Profiling Kernel-Space/User-Space Processes 24 3.6.1 Differences in Announcing and Table Sizes 24 3.6.2 Kernel-Space Issue: Reentrancy 26 3.6.3 Kernel-Space Issue: The Call Path 26 3.7 Work Done at the Application
    [Show full text]
  • Understanding the Syntactic Rule Usage in Java
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by UCL Discovery Understanding the Syntactic Rule Usage in Java Dong Qiua, Bixin Lia,∗, Earl T. Barrb, Zhendong Suc aSchool of Computer Science and Engineering, Southeast University, China bDepartment of Computer Science, University College London, UK cDepartment of Computer Science, University of California Davis, USA Abstract Context: Syntax is fundamental to any programming language: syntax defines valid programs. In the 1970s, computer scientists rigorously and empirically studied programming languages to guide and inform language design. Since then, language design has been artistic, driven by the aesthetic concerns and intuitions of language architects. Despite recent studies on small sets of selected language features, we lack a comprehensive, quantitative, empirical analysis of how modern, real-world source code exercises the syntax of its programming language. Objective: This study aims to understand how programming language syntax is employed in actual development and explore their potential applications based on the results of syntax usage analysis. Method: We present our results on the first such study on Java, a modern, mature, and widely-used programming language. Our corpus contains over 5,000 open-source Java projects, totalling 150 million source lines of code (SLoC). We study both independent (i.e. applications of a single syntax rule) and dependent (i.e. applications of multiple syntax rules) rule usage, and quantify their impact over time and project size. Results: Our study provides detailed quantitative information and yields insight, particularly (i) confirming the conventional wisdom that the usage of syntax rules is Zipfian; (ii) showing that the adoption of new rules and their impact on the usage of pre-existing rules vary significantly over time; and (iii) showing that rule usage is highly contextual.
    [Show full text]
  • Scope in Fortran 90
    Scope in Fortran 90 The scope of objects (variables, named constants, subprograms) within a program is the portion of the program in which the object is visible (can be use and, if it is a variable, modified). It is important to understand the scope of objects not only so that we know where to define an object we wish to use, but also what portion of a program unit is effected when, for example, a variable is changed, and, what errors might occur when using identifiers declared in other program sections. Objects declared in a program unit (a main program section, module, or external subprogram) are visible throughout that program unit, including any internal subprograms it hosts. Such objects are said to be global. Objects are not visible between program units. This is illustrated in Figure 1. Figure 1: The figure shows three program units. Main program unit Main is a host to the internal function F1. The module program unit Mod is a host to internal function F2. The external subroutine Sub hosts internal function F3. Objects declared inside a program unit are global; they are visible anywhere in the program unit including in any internal subprograms that it hosts. Objects in one program unit are not visible in another program unit, for example variable X and function F3 are not visible to the module program unit Mod. Objects in the module Mod can be imported to the main program section via the USE statement, see later in this section. Data declared in an internal subprogram is only visible to that subprogram; i.e.
    [Show full text]
  • Cmsc 132: Object-Oriented Programming Ii
    © Department of Computer Science UMD CMSC 132: OBJECT-ORIENTED PROGRAMMING II Iterator, Marker, Observer Design Patterns Department of Computer Science University of Maryland, College Park © Department of Computer Science UMD Design Patterns • Descriptions of reusable solutions to common software design problems (e.g, Iterator pattern) • Captures the experience of experts • Goals • Solve common programming challenges • Improve reliability of solution • Aid rapid software development • Useful for real-world applications • Design patterns are like recipes – generic solutions to expected situations • Design patterns are language independent • Recognizing when and where to use design patterns requires familiarity & experience • Design pattern libraries serve as a glossary of idioms for understanding common, but complex solutions • Design patterns are used throughout the Java Class Libraries © Department of Computer Science UMD Iterator Pattern • Definition • Move through collection of objects without knowing its internal representation • Where to use & benefits • Use a standard interface to represent data objects • Uses standard iterator built in each standard collection, like List • Need to distinguish variations in the traversal of an aggregate • Example • Iterator for collection • Original • Examine elements of collection directly • Using pattern • Collection provides Iterator class for examining elements in collection © Department of Computer Science UMD Iterator Example public interface Iterator<V> { bool hasNext(); V next(); void remove();
    [Show full text]
  • Iterators in C++ C 2016 All Rights Reserved
    Software Design Lecture Notes Prof. Stewart Weiss Iterators in C++ c 2016 All rights reserved. Iterators in C++ 1 Introduction When a program needs to visit all of the elements of a vector named myvec starting with the rst and ending with the last, you could use an iterative loop such as the following: for ( int i = 0; i < myvec.size(); i++ ) // the visit, i.e., do something with myvec[i] This code works and is a perfectly ne solution. This same type of iterative loop can visit each character in a C++ string. But what if you need code that visits all elements of a C++ list object? Is there a way to use an iterative loop to do this? To be clear, an iterative loop is one that has the form for var = start value; var compared to end value; update var; {do something with node at specic index} In other words, an iterative loop is a counting loop, as opposed to one that tests an arbitrary condition, like a while loop. The short answer to the question is that, in C++, without iterators, you cannot do this. Iterators make it possible to iterate through arbitrary containers. This set of notes answers the question, What is an iterator, and how do you use it? Iterators are a generalization of pointers in C++ and have similar semantics. They allow a program to navigate through dierent types of containers in a uniform manner. Just as pointers can be used to traverse a linked list or a binary tree, and subscripts can be used to traverse the elements of a vector, iterators can be used to sequence through the elements of any standard C++ container class.
    [Show full text]