MATLAB – Commands ”; Previous Next MATLAB is an interactive program for numerical computation and data visualization. You can enter a command by typing it at the MATLAB prompt ”>>” on the Command Window. In this section, we will provide lists of commonly used general MATLAB commands. Commands for Managing a Session MATLAB provides various commands for managing a session. The following table provides all such commands − Command Purpose clc Clears command window. clear Removes variables from memory. exist Checks for existence of file or variable. global Declares variables to be global. help Searches for a help topic. lookfor Searches help entries for a keyword. quit Stops MATLAB. who Lists current variables. whos Lists current variables (long display). Commands for Working with the System MATLAB provides various useful commands for working with the system, like saving the current work in the workspace as a file and loading the file later. It also provides various commands for other system-related activities like, displaying date, listing files in the directory, displaying current directory, etc. The following table displays some commonly used system-related commands − Command Purpose cd Changes current directory. date Displays current date. delete Deletes a file. diary Switches on/off diary file recording. dir Lists all files in current directory. load Loads workspace variables from a file. path Displays search path. pwd Displays current directory. save Saves workspace variables in a file. type Displays contents of a file. what Lists all MATLAB files in the current directory. wklread Reads .wk1 spreadsheet file. Input and Output Commands MATLAB provides the following input and output related commands − Command Purpose disp Displays contents of an array or string. fscanf Read formatted data from a file. format Controls screen-display format. fprintf Performs formatted writes to screen or file. input Displays prompts and waits for input. ; Suppresses screen printing. The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes − Format Code Purpose %s Format as a string. %d Format as an integer. %f Format as a floating point value. %e Format as a floating point value in scientific notation. %g Format in the most compact form: %f or %e. n Insert a new line in the output string. t Insert a tab in the output string. The format function has the following forms used for numeric display − Format Function Display up to format short Four decimal digits (default). format long 16 decimal digits. format short e Five digits plus exponent. format long e 16 digits plus exponents. format bank Two decimal digits. format + Positive, negative, or zero. format rat Rational approximation. format compact Suppresses some line feeds. format loose Resets to less compact display mode. Vector, Matrix and Array Commands The following table shows various commands used for working with arrays, matrices and vectors − Command Purpose cat Concatenates arrays. find Finds indices of nonzero elements. length Computes number of elements. linspace Creates regularly spaced vector. logspace Creates logarithmically spaced vector. max Returns largest element. min Returns smallest element. prod Product of each column. reshape Changes size. size Computes array size. sort Sorts each column. sum Sums each column. eye Creates an identity matrix. ones Creates an array of ones. zeros Creates an array of zeros. cross Computes matrix cross products. dot Computes matrix dot products. det Computes determinant of an array. inv Computes inverse of a matrix. pinv Computes pseudoinverse of a matrix. rank Computes rank of a matrix. rref Computes reduced row echelon form. cell Creates cell array. celldisp Displays cell array. cellplot Displays graphical representation of cell array. num2cell Converts numeric array to cell array. deal Matches input and output lists. iscell Identifies cell array. Plotting Commands MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting − Command Purpose axis Sets axis limits. fplot Intelligent plotting of functions. grid Displays gridlines. plot Generates xy plot. print Prints plot or saves plot to a file. title Puts text at top of plot. xlabel Adds text label to x-axis. ylabel Adds text label to y-axis. axes Creates axes objects. close Closes the current plot. close all Closes all plots. figure Opens a new figure window. gtext Enables label placement by mouse. hold Freezes current plot. legend Legend placement by mouse. refresh Redraws current figure window. set Specifies properties of objects such as axes. subplot Creates plots in subwindows. text Places string in figure. bar Creates bar chart. loglog Creates log-log plot. polar Creates polar plot. semilogx Creates semilog plot. (logarithmic abscissa). semilogy Creates semilog plot. (logarithmic ordinate). stairs Creates stairs plot. stem Creates stem plot. Print Page Previous Next Advertisements ”;
Category: Computer Programming
MATLAB – Colon Notation
MATLAB – Colon Notation ”; Previous Next The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations. If you want to create a row vector, containing integers from 1 to 10, you write − Live Demo 1:10 MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 − ans = 1 2 3 4 5 6 7 8 9 10 If you want to specify an increment value other than one, for example − Live Demo 100: -5: 50 MATLAB executes the statement and returns the following result − ans = 100 95 90 85 80 75 70 65 60 55 50 Let us take another example − Live Demo 0:pi/8:pi MATLAB executes the statement and returns the following result − ans = Columns 1 through 7 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562 Columns 8 through 9 2.7489 3.1416 You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays. The following table describes its use for this purpose (let us have a matrix A) − Format Purpose A(:,j) is the jth column of A. A(i,:) is the ith row of A. A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A. A(j:k) is A(j), A(j+1),…,A(k). A(:,j:k) is A(:,j), A(:,j+1),…,A(:,k). A(:,:,k) is the kth page of three-dimensional array A. A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on. A(:) is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A. Example Create a script file and type the following code in it − Live Demo A = [1 2 3 4; 4 5 6 7; 7 8 9 10] A(:,2) % second column of A A(:,2:3) % second and third column of A A(2:3,2:3) % second and third rows and second and third columns When you run the file, it displays the following result − A = 1 2 3 4 4 5 6 7 7 8 9 10 ans = 2 5 8 ans = 2 3 5 6 8 9 ans = 5 6 8 9 Print Page Previous Next Advertisements ”;
MATLAB – Strings
MATLAB – Strings ”; Previous Next Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt − Live Demo my_string = ”Tutorials Point” MATLAB will execute the above statement and return the following result − my_string = Tutorials Point MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above − whos MATLAB will execute the above statement and return the following result − Name Size Bytes Class Attributes my_string 1×16 32 char Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters − Example Create a script file and type the following code into it − Live Demo my_string = ”Tutorial””s Point”; str_ascii = uint8(my_string) % 8-bit ascii values str_back_to_char= char(str_ascii) str_16bit = uint16(my_string) % 16-bit ascii values str_back_to_char = char(str_16bit) When you run the file, it displays the following result − str_ascii = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial”s Point str_16bit = 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116 str_back_to_char = Tutorial”s Point Rectangular Character Array The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays. Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required. You can combine strings vertically in either of the following ways − Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed. Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters. Example Create a script file and type the following code into it − Live Demo doc_profile = [”Zara Ali ”; … ”Sr. Surgeon ”; … ”R N Tagore Cardiology Research Center”] doc_profile = char(”Zara Ali”, ”Sr. Surgeon”, … ”RN Tagore Cardiology Research Center”) When you run the file, it displays the following result − doc_profile = Zara Ali Sr. Surgeon R N Tagore Cardiology Research Center doc_profile = Zara Ali Sr. Surgeon RN Tagore Cardiology Research Center You can combine strings horizontally in either of the following ways − Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs. Example Create a script file and type the following code into it − Live Demo name = ”Zara Ali ”; position = ”Sr. Surgeon ”; worksAt = ”R N Tagore Cardiology Research Center”; profile = [name ”, ” position ”, ” worksAt] profile = strcat(name, ”, ”, position, ”, ”, worksAt) When you run the file, it displays the following result − profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center profile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center Combining Strings into a Cell Array From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length. However, a more efficient way to combine the strings is to convert the resulting array into a cell array. MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length. The cellstr function converts a character array into a cell array of strings. Example Create a script file and type the following code into it − Live Demo name = ”Zara Ali ”; position = ”Sr. Surgeon ”; worksAt = ”R N Tagore Cardiology Research Center”; profile = char(name, position, worksAt); profile = cellstr(profile); disp(profile) When you run the file, it displays the following result − { [1,1] = Zara Ali [2,1] = Sr. Surgeon [3,1] = R N Tagore Cardiology Research Center } String Functions in MATLAB MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings. Following table provides brief description of the string functions in MATLAB − Function Purpose Functions for storing text in character arrays, combine character arrays, etc. blanks Create string of blank characters cellstr Create cell array of strings from character array char Convert to character array (string) iscellstr Determine whether input is cell array of strings ischar Determine whether item is character array sprintf Format data into string strcat Concatenate strings horizontally strjoin Join strings in cell array into single string Functions for identifying parts of strings, find and replace substrings ischar Determine whether item is character array isletter Array elements that are alphabetic letters isspace Array elements that are space characters isstrprop Determine whether string is of specified category sscanf Read formatted data from string strfind Find one string within another strrep Find and replace substring strsplit Split string at specified delimiter strtok Selected parts of string validatestring Check validity of text string symvar Determine symbolic variables in expression regexp Match regular expression (case sensitive) regexpi Match regular expression (case insensitive) regexprep Replace string using regular expression regexptranslate Translate string into regular expression Functions for string comparison strcmp Compare strings (case sensitive) strcmpi Compare strings (case insensitive) strncmp Compare first n characters of strings (case sensitive) strncmpi
MATLAB – Syntax
MATLAB – Basic Syntax ”; Previous Next MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt. MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away. Hands on Practice Type a valid expression, for example, Live Demo 5 + 5 And press ENTER When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 10 Let us take up few more examples − Live Demo 3 ^ 2 % 3 raised to the power of 2 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 9 Another example, Live Demo sin(pi /2) % sine of angle 90o When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1 Another example, Live Demo 7/0 % Divide by zero When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = Inf warning: division by zero Another example, Live Demo 732 * 20.3 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1.4860e+04 MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for ”not a number”. Use of Semicolon (;) in MATLAB Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression. For example, Live Demo x = 3; y = x + 5 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − y = 8 Adding Comments The percent symbol (%) is used for indicating a comment line. For example, x = 9 % assign the value 9 to x You can also write a block of comments using the block comment operators % { and % }. The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments. Commonly used Operators and Special Characters MATLAB supports the following commonly used operators and special characters − Operator Purpose + Plus; addition operator. – Minus; subtraction operator. * Scalar and matrix multiplication operator. .* Array multiplication operator. ^ Scalar and matrix exponentiation operator. .^ Array exponentiation operator. Left-division operator. / Right-division operator. . Array left-division operator. ./ Array right-division operator. : Colon; generates regularly spaced elements and represents an entire row or column. ( ) Parentheses; encloses function arguments and array indices; overrides precedence. [ ] Brackets; enclosures array elements. . Decimal point. … Ellipsis; line-continuation operator , Comma; separates statements and elements in a row ; Semicolon; separates columns and suppresses display. % Percent sign; designates a comment and specifies formatting. _ Quote sign and transpose operator. ._ Nonconjugated transpose operator. = Assignment operator. Special Variables and Constants MATLAB supports the following special variables and constants − Name Meaning ans Most recent answer. eps Accuracy of floating-point precision. i,j The imaginary unit √-1. Inf Infinity. NaN Undefined numerical result (not a number). pi The number π Naming Variables Variable names consist of a letter followed by any number of letters, digits or underscore. MATLAB is case-sensitive. Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax. Saving Your Work The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory. For example, save myfile You can reload the file anytime later using the load command. load myfile Print Page Previous Next Advertisements ”;
MATLAB – Environment Setup
MATLAB – Environment Setup ”; Previous Next Local Environment Setup Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here. MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval. After downloading the installer the software can be installed through few clicks. Understanding the MATLAB Environment MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout − The desktop has the following panels − Current Folder − This panel allows you to access the project folders and files. Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>). Workspace − The workspace shows all the variables created and/or imported from files. Command History − This panel shows or return commands that are entered at the command line. Set up GNU Octave If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine. Print Page Previous Next Advertisements ”;
Lua – Variables
Lua – Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Lua is case-sensitive. There are eight basic types of values in Lua − In Lua, though we don”t have variable data types, we have three types based on the scope of the variable. Global variables − All variables are considered global unless explicitly declared as a local. Local variables − When the type is specified as local for a variable then its scope is limited with the functions inside their scope. Table fields − This is a special type of variable that can hold anything except nil including functions. Variable Definition in Lua A variable definition means to tell the interpreter where and how much to create the storage for the variable. A variable definition have an optional type and contains a list of one or more variables of that type as follows − type variable_list; Here, type is optionally local or type specified making it global, and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − local i, j local i local a,c The line local i, j both declares and defines the variables i and j; which instructs the interpreter to create variables named i, j and limits the scope to be local. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_list = value_list; Some examples are − local d , f = 5 ,10 –declaration of d and f as local variables. d , f = 5, 10; –declaration of d and f as global variables. d, f = 10 –[[declaration of d and f as global variables. Here value of f is nil –]] For definition without an initializer: variables with static storage duration are implicitly initialized with nil. Variable Declaration in Lua As you can see in the above examples, assignments for multiples variables follows a variable_list and value_list format. In the above example local d, f = 5,10 we have d and f in variable_list and 5 and 10 in values list. Value assigning in Lua takes place like first variable in the variable_list with first value in the value_list and so on. Hence, the value of d is 5 and the value of f is 10. Example Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − Live Demo — Variable definition: local a, b — Initialization a = 10 b = 30 print(“value of a:”, a) print(“value of b:”, b) — Swapping of variables b, a = a, b print(“value of a:”, a) print(“value of b:”, b) f = 70.0/3.0 print(“value of f”, f) When the above code is built and executed, it produces the following result − value of a: 10 value of b: 30 value of a: 30 value of b: 10 value of f 23.333333333333 Lvalues and Rvalues in Lua There are two kinds of expressions in Lua − lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it, which means an rvalue may appear on the right-hand side, but not on the left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and cannot appear on the left-hand side. Following is a valid statement − g = 20 But following is not a valid statement and would generate a build-time error − 10 = 20 In Lua programming language, apart from the above types of assignment, it is possible to have multiple lvalues and rvalues in the same single statement. It is shown below. g,l = 20,30 In the above statement, 20 is assigned to g and 30 is assigned to l. Print Page Previous Next Advertisements ”;
Lua – Basic Syntax
Lua – Basic Syntax ”; Previous Next Let us start creating our first Lua program! First Lua Program Interactive Mode Programming Lua provides a mode called interactive mode. In this mode, you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just the lua command. Once you type in this, press Enter and the interactive mode will be started as shown below. $ lua -i $ Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio quit to end; cd, dir and edit also available You can print something using the following statement − print(“test”) Once you press enter, you will get the following output − test Default Mode Programming Invoking the interpreter with a Lua file name parameter begins execution of the file and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Lua program. All Lua files will have extension .lua. So put the following source code in a test.lua file. Live Demo print(“test”) Assuming, lua environment is setup correctly, let’s run the program using the following code − $ lua test.lua We will get the following output − test Let”s try another way to execute a Lua program. Below is the modified test.lua file − Live Demo #!/usr/local/bin/lua print(“test”) Here, we have assumed that you have Lua interpreter available in your /usr/local/bin directory. The first line is ignored by the interpreter, if it starts with # sign. Now, try to run this program as follows − $ chmod a+rx test.lua $./test.lua We will get the following output. test Let us now see the basic structure of Lua program, so that it will be easy for you to understand the basic building blocks of the Lua programming language. Tokens in Lua A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Lua statement consists of three tokens − io.write(“Hello world, from “,_VERSION,”!n”) The individual tokens are − io.write ( “Hello world, from “,_VERSION,”!n” ) Comments Comments are like helping text in your Lua program and they are ignored by the interpreter. They start with –[[ and terminates with the characters –]] as shown below − –[[ my first program in Lua –]] Identifiers A Lua identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter ‘A to Z’ or ‘a to z’ or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). Lua does not allow punctuation characters such as @, $, and % within identifiers. Lua is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Lua. Here are some examples of the acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords The following list shows few of the reserved words in Lua. These reserved words may not be used as constants or variables or any other identifier names. and break do else elseif end false for function if in local nil not or repeat return then true until while Whitespace in Lua A line containing only whitespace, possibly with a comment, is known as a blank line, and a Lua interpreter totally ignores it. Whitespace is the term used in Lua to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int ends, and the next element begins. Therefore, in the following statement − local age There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges –get the total fruit No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose. Print Page Previous Next Advertisements ”;
Lua – Discussion
Discuss Lua ”; Previous Next Lua is an open source language built on top of C programming language. Lua has its value across multiple platforms ranging from large server systems to small mobile applications. This tutorial covers various topics ranging from the basics of Lua to its scope in various applications. Print Page Previous Next Advertisements ”;
Lua – Quick Guide
Lua – Quick Guide ”; Previous Next Lua – Overview Lua is an extensible, lightweight programming language written in C. It started as an in-house project in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes. It was designed from the beginning to be a software that can be integrated with the code written in C and other conventional languages. This integration brings many benefits. It does not try to do what C can already do but aims at offering what C is not good at: a good distance from the hardware, dynamic structures, no redundancies, ease of testing and debugging. For this, Lua has a safe environment, automatic memory management, and good facilities for handling strings and other kinds of data with dynamic size. Features Lua provides a set of unique features that makes it distinct from other languages. These include − Extensible Simple Efficient Portable Free and open Example Code print(“Hello World!”) How Lua is Implemented? Lua consists of two parts – the Lua interpreter part and the functioning software system. The functioning software system is an actual computer application that can interpret programs written in the Lua programming language. The Lua interpreter is written in ANSI C, hence it is highly portable and can run on a vast spectrum of devices from high-end network servers to small devices. Both Lua”s language and its interpreter are mature, small, and fast. It has evolved from other programming languages and top software standards. Being small in size makes it possible for it to run on small devices with low memory. Learning Lua The most important point while learning Lua is to focus on the concepts without getting lost in its technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective in designing and implementing new systems and at maintaining old ones. Some Uses of Lua Game Programming Scripting in Standalone Applications Scripting in Web Extensions and add-ons for databases like MySQL Proxy and MySQL WorkBench Security systems like Intrusion Detection System. Lua – Environment Local Environment Setup If you are still willing to set up your environment for Lua programming language, you need the following softwares available on your computer – (a) Text Editor, (b) The Lua Interpreter, and (c) Lua Compiler. Text Editor You need a text editor to type your program. Examples of a few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX. The files you create with your editor are called source files and these files contain the program source code. The source files for Lua programs are typically named with the extension “.lua”. The Lua Interpreter It is just a small program that enables you to type Lua commands and have them executed immediately. It stops the execution of a Lua file in case it encounters an error unlike a compiler that executes fully. The Lua Compiler When we extend Lua to other languages/applications, we need a Software Development Kit with a compiler that is compatible with the Lua Application Program Interface. Installation on Windows There is a separate IDE named “SciTE” developed for the windows environment, which can be downloaded from https://code.google.com/p/luaforwindows/ download section. Run the downloaded executable to install the Lua IDE. Since it’s an IDE, you can both create and build the Lua code using the same. In case, you are interested in installing Lua in command line mode, you need to install MinGW or Cygwin and then compile and install Lua in windows. Installation on Linux To download and build Lua, use the following command − $ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make linux test In order to install on other platforms like aix, ansi, bsd, generic linux, mingw, posix, solaris by replacing Linux in make Linux, test with the corresponding platform name. We have a helloWorld.lua, in Lua as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua, by switching to the folder containing the file using cd, and then using the following command − $ lua helloWorld We can see the following output. Hello World! Installation on Mac OS X To build/test Lua in the Mac OS X, use the following command − $ curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz $ tar zxf lua-5.2.3.tar.gz $ cd lua-5.2.3 $ make macosx test In certain cases, you may not have installed the Xcode and command line tools. In such cases, you won’t be able to use the make command. Install Xcode from mac app store. Then go to Preferences of Xcode, and then switch to Downloads and install the component named “Command Line Tools”. Once the process is completed, make command will be available to you. It is not mandatory for you to execute the “make macosx test” statement. Even without executing this command, you can still use Lua in Mac OS X. We have a helloWorld.lua, in Lua, as follows − print(“Hello World!”) Now, we can build and run a Lua file say helloWorld.lua by switching to the folder containing the file using cd and then using the following command − $ lua helloWorld We can see the following output − Hello World! Lua IDE As mentioned earlier, for Windows SciTE, Lua IDE is the default IDE provided by the Lua creator team. The alternate IDE available is from ZeroBrane Studio, which is available across multiple platforms like Windows, Mac and Linux. There are also plugins for eclipse that enable the Lua development. Using IDE makes it easier for development with features like code completion and is highly recommended. The IDE also provides interactive mode programming similar to the command line version of Lua. Lua – Basic Syntax Let us start creating our
Lua – Coroutines
Lua – Coroutines ”; Previous Next Introduction Coroutines are collaborative in nature, which allows two or more methods to execute in a controlled manner. With coroutines, at any given time, only one coroutine runs and this running coroutine only suspends its execution when it explicitly requests to be suspended. The above definition may look vague. Let us assume we have two methods, one the main program method and a coroutine. When we call a coroutine using resume function, its starts executing and when we call yield function, it suspends executing. Again the same coroutine can continue executing with another resume function call from where it was suspended. This process can continue till the end of execution of the coroutine. Functions Available in Coroutines The following table lists all the available functions for coroutines in Lua and their corresponding use. Sr.No. Method & Purpose 1 coroutine.create (f) Creates a new coroutine with a function f and returns an object of type “thread”. 2 coroutine.resume (co [, val1, …]) Resumes the coroutine co and passes the parameters if any. It returns the status of operation and optional other return values. 3 coroutine.running () Returns the running coroutine or nil if called in the main thread. 4 coroutine.status (co) Returns one of the values from running, normal, suspended or dead based on the state of the coroutine. 5 coroutine.wrap (f) Like coroutine.create, the coroutine.wrap function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. 6 coroutine.yield (…) Suspends the running coroutine. The parameter passed to this method acts as additional return values to the resume function. Example Let”s look at an example to understand the concept of coroutines. Live Demo co = coroutine.create(function (value1,value2) local tempvar3 = 10 print(“coroutine section 1”, value1, value2, tempvar3) local tempvar1 = coroutine.yield(value1+1,value2+1) tempvar3 = tempvar3 + value1 print(“coroutine section 2”,tempvar1 ,tempvar2, tempvar3) local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2) tempvar3 = tempvar3 + value1 print(“coroutine section 3”,tempvar1,tempvar2, tempvar3) return value2, “end” end) print(“main”, coroutine.resume(co, 3, 2)) print(“main”, coroutine.resume(co, 12,14)) print(“main”, coroutine.resume(co, 5, 6)) print(“main”, coroutine.resume(co, 10, 20)) When we run the above program, we will get the following output. coroutine section 1 3 2 10 main true 4 3 coroutine section 2 12 nil 13 main true 5 1 coroutine section 3 5 6 16 main true 2 end main false cannot resume dead coroutine What Does the Above Example Do? As mentioned before, we use the resume function to start the operation and yield function to stop the operation. Also, you can see that there are multiple return values received by resume function of coroutine. First, we create a coroutine and assign it to a variable name co and the coroutine takes in two variables as its parameters. When we call the first resume function, the values 3 and 2 are retained in the temporary variables value1 and value2 till the end of the coroutine. To make you understand this, we have used a tempvar3, which is 10 initially and it gets updated to 13 and 16 by the subsequent calls of the coroutines since value1 is retained as 3 throughout the execution of the coroutine. The first coroutine.yield returns two values 4 and 3 to the resume function, which we get by updating the input params 3 and 2 in the yield statement. It also receives the true/false status of coroutine execution. Another thing about coroutines is how the next params of resume call is taken care of, in the above example; you can see that the variable the coroutine.yield receives the next call params which provides a powerful way of doing new operation with the retentionship of existing param values. Finally, once all the statements in the coroutines are executed, the subsequent calls will return in false and “cannot resume dead coroutine” statement as response. Another Coroutine Example Let us look at a simple coroutine that returns a number from 1 to 5 with the help of yield function and resume function. It creates coroutine if not available or else resumes the existing coroutine. Live Demo function getNumber() local function getNumberHelper() co = coroutine.create(function () coroutine.yield(1) coroutine.yield(2) coroutine.yield(3) coroutine.yield(4) coroutine.yield(5) end) return co end if(numberHelper) then status, number = coroutine.resume(numberHelper); if coroutine.status(numberHelper) == “dead” then numberHelper = getNumberHelper() status, number = coroutine.resume(numberHelper); end return number else numberHelper = getNumberHelper() status, number = coroutine.resume(numberHelper); return number end end for index = 1, 10 do print(index, getNumber()) end When we run the above program, we will get the following output. 1 1 2 2 3 3 4 4 5 5 6 1 7 2 8 3 9 4 10 5 There is often a comparison of coroutines with the threads of multiprogramming languages, but we need to understand that coroutines have similar features of thread but they execute only one at a time and never execute concurrently. We control the program execution sequence to meet the needs with the provision of retaining certain information temporarily. Using global variables with coroutines provides even more flexibility to coroutines. Print Page Previous Next Advertisements ”;