Learn Lua in an Hour

Just another WordPress site

Learn Lua in an Hour

hi I’m Tyler in this video I’m going to cover the Lua programming language in about one hour I previously wrote a post called learn low in 15 minutes that post is basically a quick reference that you can use to just get started a very shallow understanding of the language or to refresh your memory if you already know it the idea of this video is to take another step towards really mastering the language of Lua I’m going to cover what I consider to be all of the core of the language which isn’t 100 percent of everything that you can do with look but it does cover most of what you’ll use day-to-day Lua is currently at version 5.3 and I will cover versions 5.1 5.2 and 5.3 which is pretty easy because they’re all basically the same I just have to highlight the the small number of differences between those languages those versions you might care about older versions of Lua because some siaps will have an older version of Lua embedded in them or if you’re using Lua jits which is the just-in-time compiler then you are going to be using version 5.1 at least at the time of making this video that’s true this is the first and what I envision as being a series of Louisville tutorials covering more and more advanced topics in Lua you don’t have to watch the rest you just want to know how to program Lua this is the only video you need to watch but I can imagine future videos covering the standard library or the C API basically the topics in this book this is the official Lua book so let’s dive into the language let’s get started ok let’s get started with the docs and how to install Lua the official website is Lua org if I click on documentation I can see the official book called programming in Lua the third edition is the latest right now the first edition is available online you can read the entire thing for free it’s useful but it covers an older version of the language another great resource is the reference manual this is basically like a set of man pages for Lua it covers the capi the standard library and all of the core language itself it’s not a great way to learn but once you know the language it is a great way to look up things you may have forgotten or technical detail you almost know but you need to double check if I click on the download link I can download a gzip file once that’s unzipped well these instructions here include downloading and unzipping the highlighted instructions here will work you through downloading and building on Linux to build on Mac OS X you just have to replace the word Linux here with Mac OS X or you could use homebrew you just type in brew install Lua on Windows you can use the Lua for Windows project at Google code I haven’t used this myself but it looks good so I think it will probably work off as far as the interpreter goes once you’ve installed you can just type Lua at the shell and now you can type in statements directly if you want to evaluate an expression you can’t just type an expression at least not with Lua 5.2 and earlier you have to make put in an equal sign as the first character of the line and then it will evaluate the expression after the equal sign ctrl D escapes on the interpreter you can use your favorite text editor to type in a Lua script oops and then you can type in at the shell Lua and then the name of your script file and it will execute it if you know the absolute path of your Lua interpreter then you can insert a first line which is hash-bang followed by the path of your interpreter make sure that your file has execute permissions and then you can execute that file directly that’s three ways to run Lua code you can also run from embedded apps okay let’s talk about types these are all eight types in Lua I’ll mainly talk about these six highlighted types in this video true and false are the boolean types the built-in type function returns a string indicating the type of the input there’s a single number type you can type numbers in standard decimal notation and scientific notation or in hex like this it’ll 5.2 and earlier numbers are represented internally 64-bit doubles by default so a 5.3 still has a single number type but it can internally use either an integer or a double representation the built in to

number function converts numbers and strings to numbers Lewis strings are immutable you can use single or double quotes to specify them and it doesn’t really make any semantic difference which type of quotes you use these literals can have the usual back slashes like new lines and tabs Lewis strings internally are arbitrary length byte sequences so 0 bytes are allowed you can type a backslash followed by up to 3 decimal digits to specify arbitrary bites and multi-line strings can be input by typing in to open square brackets and they don’t allow escapes within this type of string the built in to string function returns reasonable string representation of any value tables are key value maps and Lewis only container type I’m going to cover those later in the video the nil value conceptually means no value undefined variables evaluates a nil it’s not an error if you’ve set a variable to nil you undefined it and allow it to be garbage click you can also explicitly call collect garbage but usually don’t have to because the garbage collector is running automatically functions can be assigned to variables and passed into and out of other functions I’m going to talk more about functions later in the video user data and threads are slightly advanced types that I won’t cover in detail now a user data object is basically a black box type used by library to rap sea-level struts like a file star MCS standard i/o library thread is a co-routine instance assignments are global by default use local to make them local let’s talk about operators Lua has the usual arithmetic operators it also adds exponentiation so this is 3 squared times 2 plus 1 division is always performed as a floating-point operation even if the inputs are integer values Lua has a very clean modulo operator it’s capable of handling modulo with non integer even negative inputs there’s also a hash operator which gives us the length of a string and works on table as we’ll see later in the video Lua has the usual conditional operators or comparison operators in the case of the not equal to operator it’s spelled with a tilde as the first character when you compare two values that are have different types who always considers them not equal to each other on Lua also has the standard less than greater than operators in the case of strings that tries to put the strings in alphabetical order using the current locale the string concatenation operator and is the double dot nil and false are the only false e values in Lua which is interesting because that means zero is considered true the– the boolean operators are short-circuited which means that as soon as Lua can determine the total value of the or or the and clause it doesn’t even bother to evaluate the rest of the expressions like that I’ll quickly mention how you can work with binary operators with 5.2 has a bit 32 module which offers them as functions Lua 5.3 actually adds these operators to the language itself Louis supports assignments with multiple variables on the left and multiple expressions on the right Lua performs this operation by first evaluating everything on the right putting it on a stack and then making the assignments to the left-hand side this is important because it enables things like the swap operation I just performed if there are more variables on the left on the right the extra variables become nil if there are more expressions on the right-hand side then everything is evaluated but the extra expressions are thrown away rules are Lois only container type their associative arrays which are key value dictionaries built using hash tables I can set up an empty table by using an open and close curly bracket like this from there I can set values using this dot syntax I can also perform lookups this dot syntax treats the keys as strings and only works for identifiers which means that the strings can only contain alphanumeric or underscore characters I can also perform lookups on undefined keys which returns nil without an error however if I try to perform a look-up on a nil as if it were a table that will be an error glue also has a square bracket notation which allows me to use arbitrary Lua expressions as keys here’s an example of a number of the key via the variable a here’s an example all the table as a key and here’s an example of a function as a value called a

function like this lua also has a syntax to specify non empty tables in this case i’m creating a table with the keys a b c and d EF this syntax works by treating the left-hand side as a string key it has to be an identifier the right-hand side of the equal sign is an arbitrary Lua expression here’s an example with a function on the right-hand side if you want to specify non identifiers as keys you can use a square bracket notation like this if a table has consecutive number keys starting at 1 then it’s called an array arrays aren’t a new type there are just tables with a specific key structure in Lua syntax I can specify a a by omitting the equal signs in the table literal this is the first four prime numbers when I use this syntax Lua assigns keys as numbers starting at 1 and going up from there I can use the hash operator to see the size of an array tables in Lua are considered equal only if they’re identical it is not enough for their contents to be the same like this in other words the expressions that are being compared have to evaluate to literally the same table we’ve already been using the built-in print statement this statement takes a variable number of parameters it calls to string on each of those parameters joins them with tab characters adds a newline to the end and sends that all to standard out let’s talk about functions and closures closure is a function that refers to variables declared outside of itself but which are not Global’s for this part of the video I’m going to use a text editor to write my Lua because in practice you’ll be using a text editor to write your code and multi-line Lua doesn’t work as well in the interpreter I have to clear the global function here called ABC syntax for functions always starts with the word function and ends with the word end within the interpreter I can use the built-in du5 function to load and execute the script that’s what the do file function does now I can call ABC with any three values that I like like this similar to flexible assignments Lua function calls except flexible number of parameters if I call ABC with a single parameter then the extra variables inside the function receive the nil value if I call the function with extra values the extra values are discarded return values work similarly I can accept more or fewer values than are actually returned by the function now I’m going to define a function that returns four values when you change function calls together the output of one function goes into the put of another similarly to flexible assignment so in this example the extra return value seven will be discarded you can also create anonymous functions this syntax is the same except that you leave out the name of function here is an example that returns an empty to an empty table and you can create local functions that means the function considered as a variable only has local scope this is useful when you’re writing a module you want to call an internal function that isn’t visible outside the scope of the module let’s take a look at an example of a closure I’m going to define a function called adder which takes a number called X and returns an anonymous function which adds up a new number Y and X I’ll load these into lua now i can make a new variable called add 1 which is the return value of adder 1 and add 30 which is return value added 30 these are different functions and when i call them with the same input say 12 i’ll get different outputs the important thing here is that each of these functions has its own private copy of the variable x with a different value if closures are new to you this is a basic example to see the general idea the word chunk in lua means any block of statements that are compiled as a unit the most obvious example is a lua file i’ll create a new file to demonstrate chunks are always treated as the body of the function which has two consequences first local variables are not visible outside chunk second you can return values which stops the execution of the

chunk in the interpreter I’ll use the built-in do file function to execute the script I just wrote the global X is left undefined since it was a local in the file global Y is defined and the return value R has been received from the function any code executed in the interpreter is compiled as a chunk this means that variables declared as local aren’t visible and the next chunk like this they are visible within the same chunk though semicolon by the way is an optional line separator in lua i can also return values from an interpreter line like this the default action of the interpreter is to print out the return values in lua 5.2 and later there’s a nice built-in function called load which accepts a string compiles it as a lure chunk and returns a function you can call to execute that chunk with 5.1 which i’m using here you want to call load string to perform the same action here is an example notice that my code hasn’t run yet it’s only been compiled so far i can call f to run the chunk lua has two types of comments single line and multi-line to illustrate that I’ll create a new lua file here is a regular luis statement if at any point louis sees two hyphens then the rest of that line is a comment to start a multi-line comment you need to use two hyphens followed by to open square brackets and to show that this is in fact a multi-line comment I’m going to put in multiple lines and we’ll see that they are not executed and to show that this is the end and things are executed again I’ll create another statement when I run this we should only see strings one in five printed out because the rest are commented there you go Lua has several loop constructs I’ll start by looking at the while loop in a new Lua script we can create a loop that begins with the keyword while followed by conditional the keyword do and then an arbitrary block of statements followed by the keyword end this will count from one to ten and print out the results to verify that I’ll run the script let’s talk about four loops I’ll start a new script simple for loop starts with keyword four and it includes a number range over which will iterate a loop variable just like the while loop you want to include the body of loop between the do and end keywords we can also use a step parameter in that case we add a third parameter to the parameters being used for the for loop and you can probably guess what these do just by looking at them maybe the only non-trivial thing is that both the starting and the ending numbers are included when I execute the loop there we go there is another type of for syntax in Lua using what’s called an iterator I’m not going to cover them in detail but I will cover in a few minutes the pair’s and I pairs functions which are the most useful iterators that little comes with Lua includes a break statement but not a continue statement I’ll give you an example of break we’ll print the first number and this will stop as soon as the keyword break is seen so I’d only print the first number Lua also has a repeat until loop which is like a do-while loop the syntax is to begin with the keyword repeat followed by block of statements keyword until and then an ending condition we can confirm that this prints out 1 through 5 by running the script there you go Lua 5.2 added the go-to statements I’m not going to cover that in detail in this video in my experience the vast majority of code works well with the loop constructs we’ve already covered not using go-to although I also feel that in rare cases a go-to is the best control flow mechanism to use ipears functions allow us to iterate over tables I’ll demonstrate by defining a table with three key value pairs we can use an iterator with a special form of the for loop using the in keyword like this I’ll print out all the key value pairs in the table the first loop variable which is K here gets the keys from the table the second which is

V here gets the values tables don’t store any order information about keys and we don’t get any guarantees about the order of iteration I can also use a single loop variable if I only care about the keys if I only care about the values then I do need to use two loop variables but as a convention to other programmers I can set and underscores the first loop variable this indicates that I don’t really care about the value stored in the underscore variable the ipears function works with arrays so I’ll define an array with some Fibonacci numbers in it syntax to use I pairs is the same as for pairs like this the difference is that I pairs expects its input table to be an array and that iterates over keys in order starting from one to summarize use I pairs to iterate over an array that needs to be processed in order otherwise use pairs the if statement in lua is straightforward I’ll start by giving a very simple example you start with keyword if a condition the keyword then followed by any block of statements and the keyword end it does what you would expected to do I’ll show you a more complicated example now you can have an else if clause and you can have an else clause both of those are optional you could have one without the other or just have the if clause by itself so far we know how to print to standard out using the print function now I’m going to talk about two functions in the standard library called IO dot IO dot right I is is a table it’s a table that has some functions as some of its values it’s part of the standard library and if you’re using Lua from an embedded app such as a game the developers may have chosen to exclude some of the modules of the standard library or all of them for security reasons probably so it’s not guaranteed that you have access to these functions by default such as in the interpreter you do have access to these functions though so I’m going to tell you about them since they’re very useful the default action of IO dot read is to read a line from standard in the return value is a string with the line however it excludes the newline character at the end of the line you can also use IO dot read by giving it a number parameter this asks IO dot read to read up to that many characters from standard in as you can see in this example the variable S will have four characters IO dot write X very similarly to print I’ll give it a string as input here one thing that’s interesting is that the string contained a new line and iouder that write did not add a new line that’s the way IO dot write behaves print on the other hand if I give it the same string will add a new line IO dot write also accepts multiple parameters if it takes a number as an input then it converts that to a string otherwise that only accepts strings it concatenates multiple parameters together without any spaces between them and never adds a new line at the end like that the IO table is an example of a module the word module in lua basically means library the built-in require function is the standard way of including modules it’s sort of like an import statement in Python or a pound include in c-like languages in order to demonstrate modules I’ll build a simple one call baek-moo ax this will be a module that works with vectors two-dimensional vectors I’ll start by defining a function that computes the norm of a vector the norm of a vector is basically its distance from zero I’ll also define a distance function which computes the distance between any two given two-dimensional vectors I can reuse this norm function to help me with that calculation like this remember that chunks are compiled as the body of a function so a good way to get the neck table out is to return the value next I’m going to describe three functions building up in complexity to the require function simplest is the load file function which loads a blue a file compiles it as a chunk and then returns a function which will execute a chunk load file itself does not actually

run with code if I call the function then the code is finally run so now I should have a table in the Veck variable and I can call functions on it for example here’s the norm of 1 comma 1 the next function in complexity is the function do file which works very similarly load file except that it also takes the extra step of actually executing that code and returning the value from the chunk so we will have the same functions as veca buf the last function that I’ll describe is the require function the first difference you’ll notice is that I don’t have to add the dot Lua file name extension at the end of require now this is actually a different table than the previous two values although it has the same functionality one difference between require and do file is that require caches its values so if I call it again with the same input it will actually give me the same return value as before it in as opposed to re executing the module the final difference is that require searches through a path specified in the package that path string so it will look in multiple locations for your Lua files it’s a common practice to assign the return value of a require call to a variable of the same name as the module like this there’s two categories of errors that can be communicated across function calls the first category includes exception like errors the second includes errors given by return values the documentation avoids words like exception throw and catch but I’m going to use the exception language because I think it clearly communicates the behavior that’s going on here first I’ll show you an example of the standard library throwing an error which is then caught by the interpreter and print it in this case there’s a bad argument to the IO dot write function if you want to throw custom exception error then you can call the built in error function with a string describing the error in this case my function f will throw that error the interpret will catch it and print my error message the built-in assert function accepts as input a boolean and an error message it throws the error message if the boolean is false like this however if the condition is true then it simply returns the inputs that it receives like that common pattern in lua for functions that return error messages is to first return a boolean indicating success or failure followed by in the success case the useful return values or in the failure case and error message assert works well with its pattern I’ll demonstrate by creating two functions that return success or failure depending on which one I call and we’ll see that sort easily wraps these function calls in this case it’ll throw the error message and in this case the good case it will simply return the useful return values the built in P call function makes protected function calls basically wraps a call to catch exceptions you use it by first sending in the function that you want to call followed by the parameters that you want to give to it it calls the function with the given parameters the first return value is going to be boolean indicating success or failure and the others are either going to be the called functions return values or an error message if an exception is thrown I’ll give an example of a case where an exception is thrown summary P call converts exception like errors into return value errors I like to think of it as sort of inverse of the assert function there’s another built-in function called XP call which offers basically the same functionality as P call except that one of its input parameters is a callback function to handle exception like errors going to talk about what I think are the most useful functions in Lewis standard library we’ll start with file operations you can open files in Lua with the i/o dot open function like this first argument is the file name and then the mode just like F open at C W means write mode and you can use our for read mode you can write to a file by using the write method giving it the string that you want to write I used a colon here instead of a period because the write method treats F as an object being acted upon I’ll talk more about the colon syntax later you can close the file by

using the close method reading a file is the same except that we use the read method this method has the same input structure as iodine here’s an example there we go next I’ll talk about the pieces of the math module that I find most useful you can find the square root of a number using the math that square root function the math dot random function behaves differently depending on the number of inputs it receives with no inputs it returns a pseudo-random float between 0 and 1 it can equal 0 but is always less than 1 with one input returns a pseudo random integer between 1 the input including both endpoints as possible outputs with two inputs return the pseudo random integer between the two inputs again the endpoints are possible outputs the math module has common trig functions which work in radians pi is available as math pi now for some functions in the string module the string dot sub function returns the substring of its first input between two indices given as parameters here’s an example both endpoints are included in this example C is the fourth letter and E is the seventh you can also use string dot sub as a method call with the colon syntax like this remember that Lewis strings are arbitrary byte sequences the string dot byte function returns the numeric value of a byte within a string like this again you can call it as a method call using : syntax like this the string dot format function works like the printf function found in many other languages here’s an example I won’t cover Lewis format specifiers in detail but they are mostly the same as those in C now we’ll cover meta tables every table in lua has an optional property called a meta table it’s completely separate from the key value data and is set to nil by default meta tables allow us to add object-oriented behavior to tables among other things with meta tables we can overload operations performed on tables most useful operations to overload are the getting and setting of key value pairs which is the only meta table usage I’ll cover carefully in this video we can set a tables meta table using the built-in set meta table function like this the first parameter is the table whose meta table is being set the second is the meta table itself the first input is also the return value even though key a exists in the meditate oh it doesn’t exist in t itself only special keys in a meta table can change a tables behavior I’ll mention a couple of these special keys in just a second we can get a table’s meta table using the built in get Matt a table function like this let’s change the behavior of T by providing a backup table if the key isn’t in T Lowell will look for it in the backup double underscore index as a key in a meta table is known to Lua as providing a way to handle failed key lookups if the index value is another table then Lua will use that other table as a backup location to find key value pairs keys already in T itself will overshadow any values the backup table like this we’ll see in a minute that this functionality enables a kind of class inheritance behavior we can also overload a tables behavior when a key value pair is set for a new key this works by setting a function as the value of the double underscore new index key in a meta table this function is called by Lua with the table key and value being set as parameters here’s an example we try to set a new key and T T’s meta table has a new index function so that function is called instead of setting the value our function could have saved the data somewhere but it just printed things out the new key string is still not a key of T setting values on existing keys of T does not call our new index function this new index functionality allows us to make things like read-only tables proxy tables or tables that take action on every data access to them there are two built-in functions called Roget raw set

which can access a table’s data while ignoring its meta table I won’t cover these functions in detail but I wanted to let you know that they exist now let’s talk about using tables as classes Lua doesn’t directly contain classes but it’s easy to use tables in an object-oriented way when I talk about classes in Lua I just mean tables used so that they combine data and behavior in one place and we’re inheritance is possible when you treat a table as a class instance you want to make sure that method calls have access to the instance in C++ you would use the this pointer in Python you would use self Lua also uses a parameter called self I’m using the word method even though Lua itself doesn’t distinguish between functions and methods Louis sees them all as functions so when I say the word method what I mean is regular Lua function that meets two conditions the first condition is that it’s a value in a table used as a class and secondly it expects its first input to be a self parameter when it’s called this will all become more clear with examples now is a good time to explain : syntax for function definitions and function calls the main purpose of : syntax is to make it easier to define and call methods on tables used as classes here’s how we can define a method using regular syntax we can call the method like this when you are defining a function in a table using a colon instead of a period inserts a first input parameter called self so G and F are essentially the same when you call a function in a table using the colon inserts the table as the first parameter value past’s to the function so this is the same as this that is everything about colon syntax let’s make some example classes I’ll make two classes first is a class that can print out values from a sequence of numbers that increase by two with each step after that we’ll make a sub class based on the sequence of square numbers first I’ll type out a constructor and then I’ll use it and then I’ll explain what each line does we can use this to get a new sequence instance like this the first constructor line creates a new table that will be the returned instance the second line make sure that sequence itself has an index key pointing to itself the purpose of this is to make sequence useful as a meta table where instances will find their methods the last line sets sequence as the meta table for the new instance and returns the new instance so now we have a constructor and an instance but we can’t actually do anything yet with the instance let’s change that by defining a couple methods on the class the next method returns the next number in the sequence doesn’t actually change any state forward method does change the state of the sequence by moving forward to give a number of steps it calls the next method to find out which number is next as it takes each step now I can print out some values in the sequence like this now for something interesting we defined the forward method in a nice general way so that it doesn’t actually know anything about the sequence it just calls the next method which encapsulate s’ the order of the sequence so we can make a subclass that prints out a different sequence by overriding the next method let’s do that

for square numbers squares is a subclass so it may be surprising to see that it begins life as an instance of sequence this is actually a nice way to implement inheritance in lua it works because classes and instances are all just tables an instance behavior is based entirely on meta tables in a minute I’ll show a diagram that illustrates the relationship between the square and the sequence tables here is how we can use the square subclass yeah it works now let’s take a look at a class diagram this focuses on the three tables sq squares and sequence we’re thinking of sequence and squares as classes because they have access to a constructor and the forward and next methods when we look up a key on SQ Lua will use the first value it finds in the meta table chain so calling sq next will call the next method associated with squares not the one associated with sequence it’s interesting to carefully consider a call to sq forward because somehow the forward method has to know to call the version of next and squares and not the version in sequence even though forward itself is defined in the sequence table first Lua finds the forward key defined in sequence by looking up the meta table chain then Ford makes a call to self next what is the value of self it’s set to sq so when forward calls self neck lower begins the look up starting at the bottom of the meta table chain with sq itself so any methods defined in squares get to override methods defined in super classes like sequence this is how single inheritance works in Lua it’s also possible to use multiple inheritance in Lua which is where a class may have more than one immediate superclass I won’t cover this in detail in this video but I’ll mention that the key idea is to use a function as a meta Tables index value instead of a table actually covered all of the Lua material that I wanted to cover in this video but I’d like to end with something fun which is a concrete example using a lot of the things that we’ve just gone over in an app that will act like a graphing calculator based in the terminal it will receive a mathematical function as an input string and it will use ASCII characters to draw the graph of that function so let’s make this script I’ll call it L graph for Lua Grapher and I’ll begin with a hash-bang string so that I can call it directly from the shell without having to consciously use the loo interpreter oops and I’m going to start with a multi-line string here which is a usage string and I like to do this because programmers looking at this script can see the usage right away at the top of the file and then it’s assigned also to a global variable which I can later use to print out to the user what’s going on and right now I’m just setting up the structure I plan to explain and program this in a top-down manner meaning that I’m going to start with sort of the highest conceptual level thing happening here and define more and more detail pieces as I need them so I’m going to define a class called Grapher at the very end here I’m going to declare an instance of that class and I will call this graph method on it with arg1 arg2 special built-in variable name that the interpreter populates with the the strings that we get from the command line and – to be nice to the user if they have not given us an equation a graph instead of just having a horrible failure will notice that will print out the use of string and then we’ll exit politely now we’re ready to find the Grapher class itself so I’m going to start off with just the table of regular values not functions yet I’ll define my x window my Y window a number of columns and a ste to print out number of rows as well I’ll just hard code them for now because it’s

simple to do here is a constructor make a local table I have to make sure index key is set to self and then I’m going to return the new instance with self set as the meta table and now we’re ready to define this key function the graph function which receives a equation string as input now I’m going to delegate delegate a lot of my work to this set up care table method that I have not written yet I will write it and the idea there is that I have the self type that care table which is sort of like a two dimensional array conceptually and that will give me a way to very easily iterate over all the rows and columns as I’m doing here right now and if there is no value there if it’s nil I’ll just write a space character out if it’s not no then I’ll write whatever character is there out okay so that’s what that current code will do that’s the complete graph function and really it’s not doing any really intelligent work because I’ve delegated it all to this setup care table function which is going to do the real work here now this line is probably to be the most single interesting line because it’s actually going to do the most non-trivial work in the whole program and what I’m going to do is parse and compile equation as basically Lua code so completely insecure code security vulnerabilities there but let’s pretend the user is very friendly nice person and let me explain this dot dot dot notation so this might be confusing when Lu a compile something using load or load string dot dot is sort of like a macro that expands to the all the parameters that are given to the function f remember load string returns a function so if I were to execute this y equals f of 3 line then this code would be executed with x sets the value 3 and then let’s say eqn was set to the string x squared the sec effectively the function f would be x squared so the value of y would be 9 and really eqn could be any valid Lua expression and as long as it no depends on X and other variables then we have whatever function the user wanted to define so that makes it easier to write a graphing calculator a very insecure graphing calculator but a graphing calculator nonetheless now I have not yet written the function range mapper but I will and that function gives us exactly a linear mapping between two ranges between the beginning range in this case I’m mapping ASCII column space into the X space mathematically and then based on those two things what I can do is I can basically go through all the columns that I care about and for each column and figure out what the mathematical Y value is based on call then I can use that mathematical Y value to convert back into ASCII space that and essentially what I want to do here is I want to set self character all row to be equal to oh now it may be the case that call row can’t be set yet because call row on this ver this value right here could be nil but basically this could be the first thing I’m putting in that particular column in fact most the time we would expect that to be true Oh what if I could actually make a shortcut all the way I could just do that let’s try that out okay good so now I’ve done everything except for these two supporting functions that I haven’t defined yet but I’ve used so I defined I’ve actually used two functions that I haven’t defined yet one is called realm which is really easy this is just going to round to the nearest integer do the same as taking the floor of X plus half now this function range mapper is a little interesting because it’s going to return a function that I have to make on the fly and conceptually what I’m going to do is I’m going to

calculate this percentage that the input is from a 1 so the input is sort of a number in the range a 1 to be 1 ok so I’m just going to turn that into a percentage and then I’m going to return that percentage converted into the a 2 to be 2 range ok this is a very good chance that I’ve made some typos along the way so let’s take a look at those typos and see so um I forgot to write the word set there now let’s try this again see % from a1 there we go great only two typos so far let’s make a more interesting graph here sweet there’s a parabola on let’s do one of my favorites this zoom let’s do some mom a little trig oh yeah that’s looking good let’s do something even more interesting here’s a nice trig function I like that now I’d like to extend the functionality of this script by being able to actually draw the x axis and the y axis and I’m going to do this by sub classing the graph or class I’ll make a subclass Club access Grapher and to be honest the point of making a subclass here instead of just adding functionality to the existing class is to illustrate what it’s like to make a subclass so if I were not using this in a tutorial video I might not implement it exactly this way now I’ve set up the base class so that I really just need to override this one function set up care table in order to slightly modify the behavior of the base class now what I’m doing here is I’m making a call to the super classes version of this method and I have not used the Colden syntax in that line because I want self to be I want stuff to be the value of self that I receive in this medical but um if I used colon here then Grapher would be set itself inside the call so there’s sort of in this special case there’s sort of a case where I cannot use colon syntax I have to be very conscious of what object owns the method and which self is might be self might not be the same as where the method is so that’s that’s kind of a special case when you call super alright so now what I’ve just done is I’ve set C for column to the column that represents the y equals zero column x equals zero I’m sorry and now I’m going to iterate our over all possible rows and I will set that character to be a vertical bar we can make that a one-liner why not and now let’s draw the x-axis and so again I’m going to use range mapper to map my y equals zero value into the row value that now I can iterate over all columns and this time I’ll use a hyphen as the character that’s everything I need to do there now if I’m being careful about parsing the command-line arguments then basically the way I’m going to check if they want to use access is look for – a as a flag and if they have that flag that I expect there to be another arguments are too and so I’m going to act differently depending on whether or not the first argument is a – a if it is a – a then my global variable G will be an access scrapper instance and for convenience here I’ll copy over the math equation to graph into art 1 so that way so from this point on art 1 is always the equation graph if there was no – a will continue to use the original graph of class as the instance I’ve done everything correctly great so now I can I can even edit this instance here there we go there’s our axis all right that’s actually everything I wanted to cover in this video I

appreciate any likes please subscribe if there are any topics you’d like to request for future videos please request them in the comments I do to continue posting tutorials on programming topics in general here are links to the Twitter accounts that I have and thanks again for watching