References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters 13+16 (primarily) 2. “Lua Reference Manual” (included in Lua installation.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

1 Object Oriented Programming Ras Bodik, Thibaud Hottelier, James Ide UC Berkeley CS164: Introduction to Programming Languages and Compilers Fall 2010.
Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Objected Oriented Perl An introduction – because I don’t have the time or patience for an in- depth OOP lecture series…
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Games and Simulations O-O Programming in Java The Walker School
References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters “Lua Reference Manual” (included in Lua installation or online)
A First Program Using C#
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
Ch 21 Command Syntax Using the DIR Command with Parameters and Wildcards.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Object-Oriented Programming (OOP). Implementing an OOD in Java Each class is stored in a separate file. All files must be stored in the same package.
Variable Scope Storage Class Recursion
GP3, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 3 We start at 13:00 Slides are available from the course home page Feel free to.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Built-in Data Structures in Python An Introduction.
Games Development 2 Lua Scripting CO3301 Week 6. Contents Introducing Lua –Comparison with Python Lua Language Overview Interfacing Lua with C++
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
1 More Perl Strings References Complex data structures –Multidimensional arrays Subprograms Perl OOP –Methods –Constructors and Instances –Inheritance.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Object Oriented Programing (OOP)
1 Chapter 5: Defining Classes. 2 Basics of Classes An object is a member of a class type What is a class? Fields & Methods Types of variables: –Instance:
ENEE150 – 0102 ANDREW GOFFIN Project 4 & Function Pointers.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
OOP Basics Classes & Methods (c) IDMS/SQL News
1 Lecture 14 Data Abstraction Objects, inheritance, prototypes Ras Bodik Shaon Barman Thibaud Hottelier Hack Your Language! CS164: Introduction to Programming.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
More About Objects and Methods
Python’s Modules Noah Black.
Lua Extending References:
Arrays An array in PHP is an ordered map
More About Objects and Methods
CS2011 Introduction to Programming I Objects and Classes
Java Inheritance.
Lecture 12: Message passing The Environment Model
Review for Final Exam.
How to organize and document your classes
CIS 199 Final Review.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Java IDE Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Lab4 problems More about templates Some STL
JavaScript.
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Presentation transcript:

References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters (primarily) 2. “Lua Reference Manual” (included in Lua installation or online)

Overview  Lua doesn't have a separate OOP facility.  It does have means to "coerce" tables into classes. Not as pretty as python… We'll need to look at Metatables (ch. 13)  We'll also look at (the hard way of) creating modules Why the hard way? A: It's how we'll have to do it in ssuge.

Normal "missing" behavior  If Lua can't find a variable, it returns nil A global variable A member of a table [sample2_01.lua] x = 10 a = {x = 13, y = 15} print(x) print(a.x) print(a["x"])-- 13 print(y) -- nil print(a.y) print(a.z) -- nil print(a["z"])-- nil

Functions and Tables  Functions are "first-class" citizens in Lua.  You can store them in variables. Normal variables or table entries. [Sample2_01.lua, cont.] function foo(test) print("Hello! You gave me '".. test.. "'") end bar = foo foo("blah") -- “Hello! You gave me ‘blah’” bar("argh") -- “Hello! You game me ‘argh’” a.func_member = foo a.func_member("joust!") --or... a = {x = 13, y = 15, func_member = function() -- (as before – end } a.func_member("yow") -- “Hello! You gave me ‘yow’”

MetaTables  A metatable is: A normal Lua table Can be set as the metatable for another table (or sometimes itself, oddly enough…) ○ getmetatable(tab) ○ setmetatable(tab, meta_tab) Can contain metamethods (which sometimes can be implemented as tables) ○ __index is a special one: Called when a requested key is missing Can be a table or a function (with the table and key as parameters)

MetaTables (and __index) example (sample2_02.lua) a = {x = 9, y = 13, z = 15} print(a.x) -- 9 print(a.w) -- nil print(getmetatable(a)) -- nil m = {} -- going to be a metatable m.__index = {w = 1000, q = 20000} setmetatable(a, m) print(m) -- table: 0042EE08 print(getmetatable(a)) -- table: 0042EE08 print(a.x) -- 9 print(a.w) print(a.q) print(a.b) -- nil print(rawget(a, "x")) -- 9 print(rawget(a, "w")) -- nil ( Bypasses __index ) m.__index = function(tab, key) if key == "w" then return 1000 else if key == "q" then return end

Other "meta-methods" m.__add = function(t1, t2) if getmetatable(t1) ~= getmetatable(t2) then error("You can only call this method with two m-based tabls") end r = {} -- a new instance setmetatable(r, getmetatable(t1)) -- make result of same "type" as t1 for k, v in pairs(t1) do if t2[k] ~= nil then r[k] = t1[k] + t2[k] end return r end a = {x = 5, y = 9, z = 2} b = {x = 15, z = 3} setmetatable(a, m) setmetatable(b, m) c = a + b -- c is now {x = 20, z = 5} (with a metatable of m)

Other "meta-methods", cont. m.__tostring = function(t1) s = "[m-table| " -- Count number of key-value pairs in t1 num_elem = 0 for k, v in pairs(t1) do num_elem = num_elem + 1 end -- Append elements to s count = 0 for k, v in pairs(t1) do if count < num_elem - 1 then s = s.. v.. ", " else s = s.. v.. "]" end count = count + 1 end return s end a = {x = 15, y = 3, z = 5} setmetatable(a, m) print(a) -- [m-table| 15, 3, 5] (indirectly calls __tostring) x = tostring(a) -- x now holds “[m-table| 15, 3, 5]”

OOP in Lua  We've actually already been using Lua's "OOP" facilities. Instances are tables We create another table (the class) and set the metatable of the instances.  My example's pretty much that of the book's (Ch. 16)

OOP Example, part I/3 -- The "Class" definition Account = {balance = 0} -- A normal table. It's *going* to be the -- default attribute values for instances of the -- Account "class" function Account:withdraw(amt) self.balance = self.balance - amt end -- Alternate syntax #1 -- function Account.withdraw(self, amt) -- self.balance = self.balance – amt -- end -- Alternate syntax #2 -- Account = { balance = 0, -- function withdraw(self, amt) -- self.balance = self.balance – amt -- end -- }

OOP Example, part 2/3 -- The “constructor" function function Account:new(initialTable) -- self (in this context) is the Account class. -- Our job is to make a new table (the new object) -- of "class" Account. o = initialTable or {} -- sets o to a new table if nil is passed. setmetatable(o, self) -- Makes Account the metatable for o. self.__index = self -- Note: confusing! We just set o's metatable to -- be Account. If we define an __index method, -- o will look for any missing methods / keys in -- Account. This will also (later) play a role -- in inheritance. return o end -- like “__str__” in python. function Account:__tostring() return "[Account: balance=".. self.balance.. "]" end

OOP Example, part 3/3 -- Creating instances a = Account:new({balance=1000}) -- a = Account.new(Account, {balance=1000}) (alternate syntax) print(a) -- [Account: balance=1000] a:withdraw(200) print(a) -- [Account: balance=800] b = Account:new() -- passes nil for initialTable (so no values in table) b.balance = does a lookup in Account.__index. Gets the value 0 and -- assigns to a *new* variable in b's table. That'll be used -- for b's balance in the future (Account.balance won't change) b:withdraw(100) print(a) -- [Account: balance=800] (making b didn’t change a) print(b) -- [Account: balance=100]

Inheritance  Just a (clever / obfuscated) use of metatables and it's __index field. SpecialAccount = Account:new({limit=1000.0}) -- SpecialAccount is (for now) -- an instance of Account with a new field print(SpecialAccount) -- [Account: balance=0] s = SpecialAccount:new() -- Special Account doesn't have a new method. So Lua looks in the metatable's __index table (which is -- Account) and calls its new method. Here’s the trick: -- self (in Account:new) is now SpecialAccount. So -- we’re setting __index calls to point there. But if it doesn’t have that value, it uses its __index -- method (which points to Account). print(s) -- Interesting quirk: SpecialAccount doesn't have an __index method -- in it's metatable, so Lua defaults to the default-table output. -- it’s doing -- It doesn't dig deep enough. The easy solution... SpecialAccount.__tostring = Account.__tostring print(s) -- [Account: balance = 0]

Inheritance, cont. -- We can add methods to SpecialAccount just like any “class” function SpecialAccount:getLimit() if self.limit == nil then return 0 else return self.limit end

Inheritance and "polymorphism" -- If we add methods to SpecialAccount (which have the same name -- as one in Account), they will be used instead of Account's function SpecialAccount:withdraw(amt) if amt > self:getLimit() + self.balance then error("Insufficient funds!") else self.balance = self.balance - amt -- allow a (possibly) negative amt end t = SpecialAccount:new() u = SpecialAccount:new({balance = 150, limit = 900}) --t:withdraw(100) -- Would trigger the error u:withdraw(1000) print(u) -- [Account: balance=-850]

Modules in Lua  A module is a table returned by the require statement  Lua (and the OS) search according to LUA_PATH environment variable ?;?.lua;c:\windows\?;/usr/local/lua/?/?.lua The “?” are replaced with “my_module” (here)  All non-local “things” in the module are packaged into a table. -- This is on the “user” side local foo = require “my_module” -- foo contains one function called bar. x = foo.bar()

Modules, cont.  There is a global variable package in Lua. package.path is the $PATH variable package.cpath is dll locations … package.loaded is all loaded modules  When you use require the first time it adds to package.loaded. All future references to that module go through package.loaded (much faster).

Modules, cont.  Finally, Lua keeps one more global variable, _G, which stores a reference to things in package.loaded also stores a reference to all global variables

Creating modules (the “disciplined” method) -- In “foo.lua” -- Part I: Create the module local modname = is the name of this file (require is -- passing it to us as an argument) local M = {} -- Create a new table (the module) _G[modname] = M -- insert M into _G package.loaded[modname] = M -- insert M into package.loaded -- Part II: Make local references to any external “things” local sqrt = math.sqrt local table = table -- Part III: Freeze all external access (so we don’t clutter _G) setfenv(1, M) -- Changes our environment (the 1 indicates -- we’re changing this module’s environment would be the importer, 3 would be their -- importer, etc. -- Part IV: Write the module -- Anything we create here will go into M (and so the user will be able -- to do “foo.xyz” to access it). Note: If a normal Lua “thing” isn’t -- declared in part II, it will come back as a nil reference.