lua: programming ii - university of alaska fairbanks · lua: programming ii colon operator [1/3]...

21
Lua: Programming II CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, February 1, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks [email protected] © 2017 Glenn G. Chappell

Upload: others

Post on 01-May-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming II

CS F331 Programming LanguagesCSCE A331 Programming Language ConceptsLecture SlidesWednesday, February 1, 2017

Glenn G. ChappellDepartment of Computer ScienceUniversity of Alaska [email protected]

© 2017 Glenn G. Chappell

Page 2: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewPL Categories: Dynamic PLs

Script: program associated with a software package, used to automate or configure operations. Written in the package’s scripting language.

Out of early shell scripting languages and associated text-processing tools grew the full-featured PL Perl (1987).

Similar PLs: Python (1991), Lua (1993), Ruby & JavaScript(1995). These are dynamic programming languages.

Typical Characteristics§ Dynamic type checking.§ Little text overhead in code.§ Just about everything is modifiable at runtime.§ High-level.§ A batteries-included approach.§ Imperative and block-structured, with support for OOP.§ Mostly interpreted, with compilation to byte code as an initial step.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 2

Page 3: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewIntroduction to Lua — History, Characteristics

The Lua PL originated in 1993 at the Pontifical Catholic University in Rio de Janeiro, Brazil.

Lua source tree is small, easy to include in other projects. Thus, popular as scripting language (for games, TeX, Wikipedia, etc.).

Characteristics§ Dynamic PL.§ Simple syntax. Very little punctuation. Small, versatile feature set.§ Imperative.§ Insulated from machine.§ Typing: dynamic, largely implicit. Duck typing.§ Only eight types: number, string, boolean, table, function, nil,

userdata, thread.§ First-class functions.§ Function definitions are executable statements.§ Uses strict (eager) evaluation.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 3

Page 4: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewIntroduction to Lua — Build & Execution [1/2]

Lua is nearly always interpreted. The interpreter in the standard Lua distribution compiles Lua to Lua byte code, which is system-independent. This byte code is then interpreted directly by the runtime system.

Standard filename suffix for Lua source files: “.lua”.Standard Lua interpreter includes an interactive environment.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017

Lua

Byte Code

Standard Lua InterpreterLua

Lua Byte Code Interpreter

LuaCompiler

4

Page 5: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewIntroduction to Lua — Build & Execution [2/2]

Specifying interpreters in Unix-derived operating systems.

(1) Command line. Command: interpreter. Argument: source file.

lua zzz.lua

(2) First line of source file. Shebang + interpreter path.§ Requires knowing where the interpreter is. L

#!/usr/bin/lua

(3) First line of source file. Shebang + /usr/bin/env + PL

#!/usr/bin/env lua

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 5

Page 6: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewLua: Programming I — Variables, Values, Expressions

Summary§ Main program is code at global scope.§ String literals use double quotes, single quotes, or double brackets

with a balanced number of equals signs separating each pair of brackets: "abc" and [===[abc]===] are the same.

§ Only values have types; variables are references to values.§ Multiple assignment.§ Function print does quick & dirty output. io.write is preferred.§ “..” operator does string concatenation, with automatic number-to-

string conversion.§ Type errors are flagged at runtime, when statement is executed.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 6

See prog1.lua.

Page 7: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewLua: Programming I — Functions

Summary§ A function definition begins with the keyword function.§ Variables default to global—except parameters, loop counter.§ Newlines are irrelevant.§ Call functions as usual.§ First-class functions.§ Also use keyword function to create an unnamed function.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 7

See prog1.lua.

Page 8: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

ReviewLua: Programming I — Tables

Summary§ Maps/dictionaries, arrays, objects, classes implemented using a

single PL feature: table, a key-value structure implemented internally as a hash table.

§ Table literals use braces, entries separates by commas. Key-value pair is key in brackets, equals sign, value: { …, ["a"]=56, … }

§ Access values using braces for index syntax, as in C++/Java.§ Delete a key by setting associated value to nil.§ Can mix types of keys, values.§ If a key looks like an identifier, then we can use dot syntax:

t["abc"] and t.abc are the same.§ Can put functions in tables.§ Make an array by listing values in braces without keys. Indices start

at one. arr = { 7, "abc", fibo, 5.34 }§ Length of array arr: #arr

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 8

See prog1.lua.

Page 9: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIFlow of Control

Summary§ if COND then STMTS end§ if COND then STMTS else STMTS end§ if COND then STMTS elseif COND then STMTS … end§ while COND do STMTS end§ for VAR=FIRST, LAST do STMTS end§ for VAR=FIRST, LAST, STEP do STMTS end§ break: as in C++, Java (there is no “continue”)§ Iterator-based for-in loop. Examples:

§ for k, v in pairs(TABLE) do STMTS end§ for k, v in ipairs(TABLE_AS_ARRAY) do STMTS end

We will eventually write our own iterators.§ Note: not-equal operator: “~=”.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017

Note!

9

See prog2.lua.

Page 10: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIModules [1/2]

Lua module: an importable file—the kind of thing we would make a header/source combination for in C++.

Using a module§ To import a module into other code, use the keyword require:

mymod = require "mymod"

§ Then use module members with the dot operator:

io.write(mymod.add6(15).."\n");

§ The module itself is in a file whose name is the module name plus the Lua suffix: “mymod.lua”.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 10

Page 11: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIModules [2/2]

Writing a module§ A module returns a table containing the module members.§ In the module source: initialize module object as an empty table:

local mymod = {}

§ Things we do not want to export are local.§ Things we want to export are module members.

function mymod.add6(n)return n+6

end

§ Return the module object at the end of the file.

return mymod

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 11

See mymod.lua, prog2.lua.

Page 12: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIMetatables [1/4]

A Lua table can have an associated metatable. We use a metatable to implement various special operations involving the original table. For example, Lua uses metatables to do operator overloading. A metatable also allows us to determine what happens when a nonexistent key is accessed.

We will use the latter functionality to simulate the class-object relationship in languages like C++.

Let us make a table (which is to become the metatable for another table) and put a function in it.

mt = {} -- Empty table, to be used as metatable

function mt.printYo()io.write("Yo!\n")

end

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 12

Page 13: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIMetatables [2/4]

Suppose we attempt to get the value corresponding to a key in a table, but that key is not in the table. If the table has a metatable, then, the __index item in the metatable is called—so it needs to be a function—with two arguments: the original table and the missing key. The return value of this function call is used in place of the missing value from the original table.

We set __index to return the corresponding item in the metatable.

function mt.__index(tbl, key)return mt[key]

end

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 13

Page 14: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIMetatables [3/4]

Think of mt as being like a C++ class. Now we create an “object” of that class: another table t, whose metatable will be mt.

t = {}setmetatable(t, mt)

Table t has no member f. So calling t.printYo() invokesmt.__index(t, "printYo"), which returns mt.printYo, which is then called.

t.printYo() -- Prints "Yo!"

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 14

Page 15: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIMetatables [4/4]

We can simulate a constructor by adding a creation function to the metatable.

function mt.new()local obj = {}setmetatable(obj, mt)return obj

end

Then we can create our “object” by calling the above function.

t = mt.new() -- Create new object, using mt as "class"t.printYo() -- Prints "Yo!"

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 15

See prog2.lua.

Page 16: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIColon Operator [1/3]

PLs like C++ make a strong distinction between ordinary functions and member functions: a member function knows which object it is a member of; it accesses the object via the “this” pointer.

In Lua, a function that lies in a table is not special. It is simply an ordinary function that happens to be a value associated with some table key. The function does not know it is in a table, and it certainly cannot tell which table it lies in.

It is often useful for a function to have this information, since then it can access other values in the table. We can give a function this information by passing the table as a parameter.

-- Add the given value to the x member of the table.function t.add_to_x(self, val)

self.x = self.x + valend

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 16

Page 17: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIColon Operator [2/3]

-- Add the given value to the x member of the table.function t.add_to_x(self, val)

self.x = self.x + valend

We can call function set_x as follows.

t.add_to_x(t, 17) -- Increase t.x by 17

But the above is redundant: t is specified twice. So Lua offers a shorthand, using the colon operator.

t:add_to_x(17) -- Increase t.x by 17

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 17

Page 18: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIColon Operator [3/3]

The colon operator is particularly useful when a function is in a metatable. Suppose table t has metatable mt as before.

function mt.print_x(self)io.write(self.x.."\n")

end

Now we can print t.x as follows.

t:print_x()

Using metatables and the colon operator, we can do object-oriented programming in Lua.

However, Lua offers other functionality that we may want to use instead: closures.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 18

See prog2.lua.

Page 19: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIClosures [1/3]

A closure is a function that carries with it (some portion of) the environment in which it was defined. Closures offer a simple way to do some of the things we might do with an object in traditional C++/Java OO style.

Here is a function that returns a closure.

-- make_multiplier-- Return function that multiplies by the given k.function make_multiplier(k)

function mult(x)return k*x

endreturn mult

end

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 19

See prog2.lua.

Page 20: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIClosures [2/3]

Function mult, is an ordinary function that returns its parameter multiplied by k. But what is k? It is the parameter of make_multiplier. We call the return value of make_multipliera closure, since it contains a copy of the k that was passed into this particular call to make_multiplier.

If we call make_multiplier multiple times, we can get closures with different values of k.

times2 = make_multiplier(2) -- Times-2 functiontriple = make_multiplier(3) -- Times-3 function

io.write(times2(7).."\n"); -- Prints "14"io.write(triple(10).."\n"); -- Prints "30"

1 Feb 2017 CS F331 / CSCE A331 Spring 2017 20

Page 21: Lua: Programming II - University of Alaska Fairbanks · Lua: Programming II Colon Operator [1/3] PLs like C++ make a strong distinction between ordinary functions and member functions:

Lua: Programming IIClosures [3/3]

Using a traditional OO style, we could do something like this by creating objects with k as a data member. We could set the value of k in a constructor and use it in a member function mult.

But closures are a bit simpler. So the existence of closures means we have less need for objects. In particular, if an object exists only to support one member function, which accesses various data members of the object, then we might be better off using a closure instead of an object.

Closures are found in a number of PLs. Since the 2011 standard, C++ has had closures, in the form of lambda functions.

1 Feb 2017 CS F331 / CSCE A331 Spring 2017

See closure.cpp.

21