introdução a lua, luaorb e o2gsd.ime.usp.br/integrade/workshops/ws04/... · puc-rio lua, luaorb...

41
Introdução a Lua, LuaOrb e O 2 Renato Cerqueira Departamento de Informática, PUC-Rio

Upload: others

Post on 03-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Introdução a Lua,LuaOrb e O2

Renato Cerqueira

Departamento de Informática, PUC-Rio

Page 2: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Agenda

• O que é Lua?

• Por que Lua?

• Como é Lua?

• LuaOrb

• O2

Page 3: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

O Que é Lua?

• Yet Another Scripting Language• Da mesma família de Perl, Tcl, Python, Ruby, JavaScript, etc

• Uma linguagem para a descrição de dados• Capacidade de expressão similar de XML

• Uma linguagem embutida (embeddable)

• Simples e flexível• “Coisas simples são simples, coisas complexas são possíveis”

• Um framework para novas linguagens• Ex.: CGILua, LuaOrb, LuaJava, Lua.NET, …

Page 4: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Por que Lua?

• Leve• uma linguagem simples e pequena, com poucos conceitos

• núcleo com aprox. 60K, executável completo com 140K

• Portável• escrita em ANSI C clean

• executa em PalmOS, EPOC (Symbian), Brew (Qualcomm),Playstation II, XBox, sistemas embutidos, mainframes, etc.

• Eficiente (ver benchmarks)

• Fácil de ser embutida• C/C++, Java, Fortran, Ruby, OPL (EPOC), C#, ...

Page 5: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Lua é Pequena

• Tamanhos de algumas linguagens (Solaris)• Lua 4.0: 120K

• Tcl (? < 8.0): 655K (~ 5x)

• Python 2.0: 860K (~ 6.5x)

• Perl 5.6: 1.1M (~ 8.5x)

• Seu tamanho pequeno tem outros benefícios:• Fácil de instalar

• Fácil de adaptar

• Portável

Page 6: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Lua é Eficiente

• Mais rápida que Perl, Python; muito mais rápida queTcl• Ver www.bagley.org/~doug/shootout

• Eficiente para descrição de dados• Compilador rápido

• Fácil de ser embutida em C/C++• Fácil recorrer a C quando eficiência é crítica

Page 7: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Resultados de Desempenho

4.77s (524%)0.84s (92%)0.91sAck (8)

2.91s (392%)0.69s (93%)0.74sFibo (30)

1.13s (127%)0.58s (65%)0.89sMatrix (50)

1.81s (174%)0.70s (67%)1.04sHeapsort (5e4)

1.29s (137%)0.62s (66%)0.94sSieve (100)

1.64s (159%)1.08s (105%)1.03sRandom (1e6)

Perl 5.6.1Lua 5.0Lua 4.0Programa

Page 8: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Mais Resultados

• Computer Language Shootout Scorecard• http://dada.perl.it/shootout/

• Comparações• Tempo de CPU

• Uso de memória

• Linhas de código

Page 9: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Tempo de CPU

Page 10: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Uso de Memória

Page 11: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Linhas de Código

Page 12: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

CPU + Memória

Page 13: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

CPU + Memória + LDC

Page 14: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Algumas Aplicações

• Jogos• LucasArts, BioWare, Microsoft, Relic Entertainment, Absolute

Studios, Monkeystone Games, etc.

• Outros usos• tomsrtbt: ”The most Linux on one floppy disk”

• Crazy Ivan Robot (campeão das RoboCup 2000 e 2001 naDinamarca)

• Sistema de monitoramento de pacientes com PDAs (InCor)

• Layout de chips (Intel)

• APT-RPM (Conectiva e United Linux)

• Space Shuttle Hazardous Gas Detection System (ASRCAerospace)

Page 15: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Enquete na gamedev.net

Which language do you use for scripting in your game engine?

314.51%Other

40.58%TCL

81.16%Ruby

91.31%Perl

101.45%Lisp

486.98%Python

679.75%C (with co-routines)

14120.5%Lua

18126.3%I made my own

18827.3%My engine doesn’t have scripting

Page 16: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Evolução da Linguagem

• Diretrizes• Simplicidade

• Eficiência

• Portabilidade

• Extensibilidade

• Versão 1.0• Descrição de dados

• Recursos básicos deprocessamento

• Versão 2.0• Mecanismos de

extensibilidade

• Suporte a OO

• Versão 3.0• Melhor e mais extensibilidade

• Versão 4.0• Múltiplos estados e

preocupação comconcorrência

• Versão 5.0• Programação em ponto

grande (programaçãomodular)

• Programação concorrente

• Novas Tendências• Sistemas de tempo real

Page 17: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

function fat (n) if n == 0 then return 1 else return n*fat(n-1) endend

Como é Lua?

• Sintaxe similar a Pascal

• Tipagem dinâmica

• Gerenciamento de memóriaautomático• Estruturas de dados dinâmicas

• Coleta de lixo

• Sete tipos básicos• números, booleanos, tabelas,

funções, strings, userdata, nil

Page 18: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Strings

• No size limits, good performance for long strings• common practice to read a whole text file in a single string

before processing

• Strings can store arbitrary binary data• not ‘\0’ terminated

• Pattern matching facilities, implemented through astandard library

• Pattern substitution can be called with a function tocompute the replacement string

Page 19: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Example: Decoding a URLencoding string

• This function is used by CGILua to decode a URL encoding string:• “lua%3Dis+great” → “lua=is great”

function unescape (str) str = string.gsub(str, "+", " ") str = string.gsub(str, "%%(%x%x)", function (x) return string.char(tonumber(x, 16)) end) return strend

Page 20: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Tables

• Implement associative arrays• any value (including functions and other tables) can be used

both for indices and values

• Grow and shrink dynamically• without generating garbage

• Referential semantics

• Tables implement most common data structures easilyand efficiently• arrays, records, sets, sparse arrays, tables(!), lists, etc.

Page 21: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Tables x Data Structures

• arrays: numbers as keys• very efficient• algorithm to store arrays as arrays!

• records: literal strings as keys• sugar: a.x ≡ a["x"]

• sets: values as keys

local a = {}for i=1,N do a[i] = 0end

a.x = "hello"print(a.x)

a[x] = 1 -- insert xa[y] = nil -- remove yif a[z] ... -- membership?

Page 22: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Constructors

• Expressions to create and initialize tables

• Record stylepoint = {x=10, y=20}print(point.y) --> 20

days = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}print(days[3]) --> Tue

points = {{x=0,y=0}, point; n=2}

• List style

• Mixed style

Page 23: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Constructors

• Data description uses:

book{ author="F.P.Brooks", title="The Mythical Man-Month", year=1975,}

book{ author="Jon Bentley", title = "Programming Pearls", year=1986,}

sugar for book({...})

Page 24: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Tables x Objects

• Tables are dynamically created objects

value = vnext =

listold list...

list = {value=v, next=list}

Page 25: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Functions

• First class values

function inc (x) return x+1end

inc = function (x) return x+1 end

sugar

function count (x) return function () x = x+1; return x; endenda = count(10)print(a()) --> 11print(a()) --> 12

• Lexical Scoping

Page 26: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Lexical Scoping

function newObject () local x local get_x = function () return x end local set_x = function (new_x) x = new_x end return { get_x = get_x, set_x = set_x }end

• Example: objects (again...)

Page 27: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Objects

• First class functions + tables = almost OO.• tables can have functions as field values (≅ methods)

• Syntactic sugar for defining and calling methods• handles hidden parameter self

a.foo(a,x)a:foo(x)

a.foo = function(self,x) ...end

function a:foo(x) ...end

sugar

sugar

Page 28: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Metatables

• Metatables redefine the behavior of tables (anduserdata)

• Typical example: inheritance (delegation)• field “index” in its metatable drives how a table handles absent

indices

• it can be a table (straight delegation) or a function (genericbehavior)

Page 29: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Inheritance (delegation)

b = Class:new{}print(b.x) -> 0b:add(20)print(b.x) -> 20

Class = {x = 0}Class.__index = Class

function Class:add (d) self.x = self.x + dend

function Class:new (o) setmetatable(o, self) return oend

Page 30: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

look for“index” at the

metatable

Inheritance (delegation)

b:add(20) → b.add(b, 20) → b[“add”](b, 20)b.[“add”] → nil ? metatable(b).__index[“add”] → Class.index[“add”] → Class[“add”] → <method add>

b.[“add”](b, 20) → <method add>(b, 20) →

b.x = b.x + 20

Page 31: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Coroutines

• simple (and portable) alternative for multi-threading

• powerful mechanism per se• generators, “pipes”, simulation, etc.

• Implemented as semi-coroutines• coroutine.create

• call + yield

Page 32: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Multithreading Non-Preemptive

require “luasocket”host = “www.w3.org”file = “/TR/REC-html32.html”

c = assert(socket.connect(host,80))c:send(“GET “..file..”\n”)while true do local s, status = c:receive(2^10) io.write(s) if status == “closed” then break endendc:close()

Page 33: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Multithreading Non-Preemptive

function download(host,file) local c = assert(socket.connect(host,80)) local count = 0 c:send(“GET “..file..”\n”) while true do local s, status = Receive(2^10) count = count + string.len(s) if status == “closed” then break end end c:close() return countend

Page 34: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Multithreading Non-Preemptive

-- sequential versionfunction Receive(connection) return connection:receive(2^10)end

-- concurrent versionfunction Receive(connection) connection:timeout(0) local s, status = connection:receive(2^10) if status == “timeout” then coroutine.yield(connection) end return s, statusend

Page 35: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Multithreading Non-Preemptive

threads = {}function get (host,file) local co = coroutine.create(function () return download(host,file) end table.insert(threads,co)end

host = “www.w3.org”get(host,”TR/html1401/html40.txt”)get(host,”TR/2002/REC-xhtml1-20001113/xhtml1.pdf”)get(host,”TR/REC-html32.html”)…dispatcher()

Page 36: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Multithreading Non-Preemptive

function dispatcher() while true do local n = table.getn(threads) if n == 0 then break end local connections = {} for i=1,n do local status, res = coroutine.resume(threads[i]) if not res then table.remove(threads,i) break else table.insert(connections,res) end end if table.getn(connections) == n then socket.select(connections) end endend

Page 37: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

LuaOrb

• Binding between Lua and several middleware systems• CORBA, COM, “Java”

• Dynamic binding, based on reflexivity

• Flexible type mapping• straightforward for arrays, records, strings, primitive types

obj = luaorb.createproxy(“corbaloc::hostname:6666/Id”, “InterfaceName”)

obj:foo({x=10, y=20}, {1,2,3})

Page 38: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

LuaOrb: Example

obj = lo.createproxy(“corbaloc:...”)

obj:foo({x=10, y=20}, {1,2,3})

obj.foo(obj, {x=10, y=20}, {1,2,3})

- invoke metatable- try to find method “foo”- return closure

- invoke closure, which:- convert values to expected types- invoke method- convert returned value (if any)

returns a proxy(system dependent)

Page 39: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

LuaOrb: Servers

• Objects created in Lua may be exported to the outsideworld• needs an explicit type

• Implementation needs a “generic adaptor”, to dispatchmethods• In CORBA, uses the Dynamic Skeleton Interface

• In Java, needs dynamic code generation (as of version ?)

• Same type mapping used by clients• in opposite direction

Page 40: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Mais Informações

• www.lua.org

• www.tecgraf.puc-rio.br/luaorb/

• www.tecgraf.puc-rio.br/luaorb/o2

• http://lua-users.org/

• http://bazar2.conectiva.com.br/mailman/listinfo/lua

• Livro: Programming in Lua, by Roberto Ierusalimschy

[email protected]

Page 41: Introdução a Lua, LuaOrb e O2gsd.ime.usp.br/integrade/workshops/ws04/... · PUC-Rio Lua, LuaOrb & O2 Algumas Aplicações •Jogos •LucasArts, BioWare, Microsoft, Relic Entertainment,

Lua, LuaOrb & O2PUC-Rio

Programming in Lua