Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C....

39
Lua 5.1 para Programadores Renato Maia [email protected] Pontifícia Universidade Católica do Rio de Janeiro Departamento de Informática 28 de maio de 2009

Transcript of Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C....

Page 1: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Lua 5.1 para Programadores

Renato [email protected]

Pontifícia Universidade Católica do Rio de JaneiroDepartamento de Informática

28 de maio de 2009

Page 2: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

O Que é Lua?

I Mais uma linguagem dinâmica.I Interpretação de código

code = l o a d s t r i n g ( " p r i n t ( ’ Hel lo , World ! ’ ) " )code ( ) −−> Hel lo , World !

I Tipagem dinâmicaa = 1p r i n t ( a+a ) −−> 2a = " a "p r i n t ( a+a ) −−> at tempt to perform a r i t h m e t i c on g loba l ’ a ’ ( a s t r i n g value )

I Coleta automática de lixof i l e = asser t ( i o . open ( " f i l e . t x t " , "w" ) )f i l e : w r i t e ( a )f i l e : c lose ( )f i l e = n i l −− conteudo de ‘ f i l e ’ v i r a l i x o a ser co le tado

I Reflexão computacionalfunction s t r i n g : t r i m ( )

return s e l f : match ( "^%s∗(.−)%s∗$ " )endusername = " admin "p r i n t ( username : t r i m ( ) ) −−> admin

Page 3: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

O Que é Lua?

I Linguagem de extensão estensível.I Ênfase em comunicação inter-linguagens.I Enfatiza desenvolvimento em múltiplas linguagens.

I Uma biblioteca ANSI C:#include < lua . h>#include < l u a l i b . h>#include < l a u x l i b . h>

i n t main ( i n t argc , char∗ argv [ ] ){

lua_Sta te ∗L = lua_open ( ) ;luaL_open l ibs ( L ) ;l uaL_dos t r i ng ( L , " p r i n t ( ’ Hel lo , World ! ’ ) " ) ;lua_c lose ( L ) ;return 0;

}

I Única linguagem fora do eixo EUA/Europa/Japão a seradotada mundialmente (Ruby é a única do Japão).

I É genuinamente brasileira (PUC-Rio 1993–2009).

Page 4: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Onde Lua é Usada?

“It is easy to see why Luais rapidly becoming thede facto standard forgame scripting”.

Artificial Intelligence forGames

Morgan Kaufmann2006

“It’s quite possible thatgame developers will lookback at the 2000s as thedecade of Lua”.

Game ProgrammingCharles River Media

2005

Page 5: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Onde Lua é Usada?

I Adobe Photoshop Lightroom

“Over 40% of AdobeLightroom is written in Lua.”

“So what we do with Lua isessentially all of theapplication logic from runningthe UI to managing what weactually do in the database.”

Mark HamburgFundador do projeto Adobe

Photoshop Lightroom

Page 6: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Onde Lua é Usada?

I Firmware de impressoras (Olivetty)I Analisador de protocolos (Wireshark)I Monitoramento remoto (Omnitronix)I Pós-produção de filmes (Digital Fusion, eyeon)I Servidores Web (RealTimeLogic)

Page 7: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Por Que o Sucesso de Lua?

Livre A licença de Lua é muito liberal (MIT license).Portável Escrita em ANSI C ∩ ANSI C++, sem ifdef’s.

Embarcável Se integra facilmente com outras linguagens.Pequena Fontes em torno de 17 mil linhas de código C.

Interpretador+bibliotecas == 153KB (Linux).Rápida “Lua code tends to be executed much faster than

other interpreted languages, so fast that ‘as fast asLua’ has become a proverbial expression.”

www.h3rald.com

Poderosa, mas simples “Lua gives you the power; you buildthe mechanisms.”

Programming in LuaRoberto Ierusalimschy, 2003.

Page 8: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Como é Lua?

Tipos de Dadosnil function

boolean tablenumber threadstring userdata

Operadores

Aritméticos + - * / ^

Relacionais == ~= < > <= >=

Lógicos not and or

Concaten. ..Comprim. #

Estruturas de Controle

local e , b , c = 0 , 0 , 0local l n = i o . read ( )while l n ~= n i l do

i f l n == " " thene = e + 1

e l s e i f l n : match ( "^%s&" ) thenb = b + 1

elsec = c + 1

endrepeat

p r i n t ( l n : sub (1 , 80) )l n = l n : sub (81)

u n t i l l n == " "l n = i o . read ( )

endlocal t = e+b+cfor i =1 , 80 do

i o . w r i t e (( i /80 <c / t ) and " . " or " " )

end

Page 9: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Strings

I São imutáveis.vers ion = " Lua " . . " " . . " 5.1 "i n v e r t ( vers ion )p r i n t ( vers ion ) −−> Lua 5.1

I Cada valor string é único.i f vers ion == " Lua 5.1 " then p r i n t ( " i g u a i s " ) end −−> i g u a i s

I Porém há um custo em criar novas strings, mesmo umasubstring. Em particular, o custo de concatenação é “alto”.−− ruimlocal t e x t = " "for l i n e in i o . l i n e s ( ) do

t e x t = t e x t . . l i n e . . " \ n "end

−− melhorlocal t e x t = i o . read ( "∗a " )

I Alternativas: table.concat, string.gsub, etc.

Page 10: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Funções

I São valores de primeira-classe e anônimas.p r i n t ( s t r i n g . gsub ( " Lua $MAJOR.$MINOR" , " $(%u+) " , function (name)

i f name == "MAJOR" then return 5 endi f name == "MINOR" then return 1 end

end ) ) −−> Lua 5.1 2

I Não define os parâmetros que deve receber.twoArgs = function ( a , b ) p r i n t ( a , b ) endtwoArgs (1 , 2 , 3) −−> 1 2twoArgs ( 1 ) −−> 1 n i l

I Pode retornar um número arbitrário de parâmetros. (1)

function getNums ( n )i f n == 1 then return 1 endi f n == 2 then return 1 , 2 endi f n == 3 then return 1 , 2 , 3 end

endlocal a , b = getNums ( 3 )p r i n t ( a , b ) −−> 1 2local a , b = getNums ( 1 )p r i n t ( a , b ) −−> 1 n i lp r i n t ( getNums ( 3 ) ) −−> 1 2 3

Page 11: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Manipulando Argumentos Variados

I Dando diferentes nomes aos argumentos.function process ( message , . . . )

i f message == " Request " thenlocal objec t , operat ion , args = . . .return d ispatch ( ob jec t , operat ion , args )

e l s e i f message == " Reply " thenlocal success , r e s u l t = . . .i f success then return r e s u l t ende r r o r ( r e s u l t )

endend

I A função select.function maximum ( . . . )

local max = −math . hugefor i =1 , s e l e c t ( " # " , . . . ) do

local value = s e l e c t ( i , . . . )max = value > max and value or max

endreturn max

endp r i n t (maximum(1 , 2 , 3 ) ) −−> 3p r i n t (maximum( n i l ) ) −−> at tempt to compare number w i th n i l

Page 12: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Funções

I Podem ser recursivas e realizam chamadas finais próprias(proper tail call).

function pickOS ( )i o . w r i t e ( " Pick an OS: MacOS, Linux , Windows \ n >" )local choice = i o . read ( )i f choice == "MacOS" then return pickMacOS ( ) endi f choice == " L inux " then return p ickL inux ( ) endi f choice == " Windows " then return pickWindows ( ) endreturn pickOS ( )

end

function pickMacOS ( )i o . w r i t e ( " Pick an MacOS vers ion : 1−−10 or type ’ Back ’ \ n >" )local choice = i o . read ( )i f choice == " Back " then return pickOS ( ) endlocal vers ion = tonumber ( i o . read ( ) )i f vers ion and vers ion > 0 and vers ion <= 10 then

return setOS ( "MacOS" , ve rs ion )endreturn pickMacOS ( )

end

...

Page 13: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

for Genérico

I Pode-se usar uma função para iterar num conjunto deelementos.

local function i t e r a t o r ( s t r i n g , pos )pos = pos + 1i f pos <= # s t r i n g then

return pos , s t r i n g : sub ( pos , pos )end

end

function a l l c h a r s ( s t r i n g )return i t e r a t o r , s t r i n g , 0

end

for pos , char in a l l c h a r s ( vers ion ) do −−> 1 Lp r i n t ( pos , char ) −−> 2 u

end −−> 3 a−−> 4−−> 5 5−−> 6 .−−> 7 1

Page 14: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Fechos de Função

I Funções são na realidade fechos que capturam variáveisdo escopo em que são criadas

function compose ( f , g )return function ( . . . )

return f ( g ( . . . ) )end

end

function normal ( x , y , z )local l en =( x^2+y^2+z ^2 )^ .5return x / len , y / len , z / len

end

local f = compose (maximum,normal )

p r i n t ( f ( 1 , 2 , 3 ) ) −−> 0 . 8 0 1 7 . . .

function counter ( )local cu r ren t = 0return function ( )

cu r ren t = cu r ren t + 1return cu r ren t

end , function ( )cu r ren t = cu r ren t − 1return cu r ren t

endend

local inc , dec = counter ( )p r i n t ( i nc ( ) ) −−> 1p r i n t ( i nc ( ) ) −−> 2p r i n t ( i nc ( ) ) −−> 3p r i n t ( dec ( ) ) −−> 2p r i n t ( dec ( ) ) −−> 1p r i n t ( dec ( ) ) −−> 0

Page 15: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Interpretação

I A função loadstring permite criar uma função cujocorpo é o código Lua dado pela string passada porparâmetro.

local f a t 1 = l o a d s t r i n g ( [ [local f a t = . . .for i = f a t −1, 2 , −1 do

f a t = f a t ∗ iendreturn f a t

] ] )

p r i n t ( f a t 1 ( 5 ) ) −−> 120

local f a t 2 = function ( . . . )local f a t = . . .for i = f a t −1, 2 , −1 do

f a t = f a t ∗ iendreturn f a t

end

p r i n t ( f a t 2 ( 5 ) ) −−> 120

I As demais funções que interpretam código Lua funcionamde forma similar:

I loadfile(path) : loadstring(io.open(path):read("*a"))I dofile(path) : assert(loadfile(path))()

Page 16: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Tabelas

I São vetores associativos, onde as chaves e valorespodem ser qualquer valor diferente de nil.

local tab = {[123 ] = " one two three " ,[ " do is " ] = 2 ,[ "dummy" ] = function ( ) end ,[ " t ab l e " ] = {

[ function ( ) end ] = " f u n c t i o n " ,[ { } ] = " t ab l e "

} ,}

tab [ " do is " ] = " two "p r i n t ( tab [ " do is " ] ) −−> twop r i n t ( tab [ 3 2 1 ] ) −−> n i lp r i n t ( tab [ n i l ] ) −−> n i l

for key , value in pa i r s ( tab ) do −−> dummy f u n c t i o n : 0x12fd f0p r i n t ( key , value ) −−> dois two

end −−> 123 one two three−−> tab le tab l e : 0x12fce0

Page 17: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Sequências

I Valores em índices inteiros não-negativos sãoarmazenados de forma eficiente.

local l i s t = { " a " , " b " , " c " , " d " , " e " }l i s t [ 2 ] = "B"l i s t [ 4 ] = "D"for i = 1 , # l i s t do −−> a

p r i n t ( l i s t [ i ] ) −−> Bend −−> c

−−> D−−> e

I Idiomas comuns na manipulação de listas.local l i n e s = { }for l i n e in i o . l i n e s ( ) do

l i n e s [# l i n e s +1] = l i n eendi o . w r i t e ( t ab l e . concat ( l i nes , " \ n " ) )

Page 18: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Sequências Degeneradas

I Uma sequência só é “bem formada” se não tiver “buracos”.local l i s t = { " a " , ni l , " c " , ni l , " e " }p r i n t (# l i s t ) −−> 5local l i s t = { [ 1 ] = " a " , [ 2 ] = ni l , [ 3 ] = " c " , [ 4 ] = ni l , [ 5 ] = " e " }p r i n t (# l i s t ) −−> 1

I Funções que manipulam sequências tem o mesmocomportamento.

local l i s t = { " a " , " b " , " c " , [24 ]= " x " , [ 25 ]= " y " , [ 26 ]= " z " }for index , value in i p a i r s ( l i s t ) do

l i s t [ index ] = value . . valueendp r i n t ( unpack ( l i s t ) ) −−> aa bb ccp r i n t ( t ab l e . concat ( l i s t ) ) −−> aabbcc

Page 19: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Conjuntos

I Elementos são armazenados como chave.local primes = { }for i =1 , N do

primes [ i ] = trueend

for i =2 , N^ .5 doi f primes [ i ] ~= n i l then

for j = i + i , N, i doprimes [ j ] = n i l

endend

end

p r i n t ( " Prime numbers smal le r than " . . N . . " are : " )for prime in pa i r s ( primes ) do

i o . w r i t e ( prime , " , " )end

Page 20: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Registros

I Açúcar sintático para representar registros.local contac t = {

name = " Fulano de Tal " ,mai l = " fulano@mailcatch . com" ,phone = 55212345678,fax = 55213456789,webpage = " h t t p : / / www. blog . com/~ fu lano " ,address = {

s t r e e t = "Rua Sem Fim " ,number = 321 ,posta lcode = 23456789,s ta t e = "RJ" ,c i t y = " Rio de Jane i ro " ,count ry = " B r a z i l " ,

} ,}p r i n t ( con tac t . address . count ry ) −−> B r a z i lcontac t . address . count ry = " B r a s i l "p r i n t ( con tac t [ " address " ] [ " count ry " ] ) −−> B r a s i l

Page 21: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Misturando Usos Numa Mesma Tabela

I Sequências Esparsaslocal sparse = { " a " , " b " , [ 1 0 ] = " j " , [ 1 1 ] = " k " , n = 26 }

I Conjunto Ordenadolocal l e t t e r s = { }for i =1 , 10 do

local l e t t e r = s t r i n g . char ( math . random (65 , 90) )l e t t e r s [# l e t t e r s +1] = l e t t e rl e t t e r s [ l e t t e r ] = # l e t t e r s

endp r i n t ( " Type a l e t t e r (A−Z) " )local index = l e t t e r s [ i o . read ( ) : upper ( ) ]i f index ~= n i l then

p r i n t ( " Your l e t t e r was the " . . index . . " th random l e t t e r " )else

p r i n t ( " Your l e t t e r was not generated . The l e t t e r s were : " )p r i n t ( t ab l e . concat ( l e t t e r s , " " ) )

end

Page 22: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Ambientes

I Variáveis globais são na realidade campos da tabela _G.asser t (_G[ " p r i n t " ] == p r i n t )asser t (_G. l o a d s t r i n g == l o a d s t r i n g )

I Cada função pode ter um ambiente global diferente.local sandbox = {−− i nc lude only safe f u nc t i o nsp r i n t = p r i n t ,

}local code = asser t ( l o a d s t r i n g ( [ [

p r i n t = n i los . execute ( ’ sudo rm −fR . ’ )

] ] ) )se t fenv ( code , sandbox )local success , errmsg = p c a l l ( code )i f not success then

p r i n t ( errmsg ) −−> [ s t r i n g " p r i n t = n i l . . . " ] : 2 : at tempt to index g loba l ’ os ’ ( a n i l value )end

Page 23: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Módulos

I Funções em Lua são geralmente organizadas em módulosque são tabelas que definem um espaço de nomesseparado.

p r i n t ( type ( t ab l e ) ) −−> tab lep r i n t ( type ( t ab l e . concat ) ) −−> f u n c t i o n

I A função module é fornecida para facilitar a criação demódulos em Lua.

local s e l e c t = s e l e c t

module ( " t ab l e . u t i l " )

function newset ( . . . )local set = { }for i =1 , s e l e c t ( " # " , . . . ) do

set [ s e l e c t ( i , . . . ) ] = trueendreturn set

end

r equ i re ( " t ab l e . u t i l " )

s = tab le . u t i l . newset (2 ,3 ,5 ,7 )p r i n t ( s [ 1 ] ) −−> n i lp r i n t ( s [ 2 ] ) −−> t ruep r i n t ( s [ 3 ] ) −−> t rue

Page 24: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Objetos

I Objetos são tabelas contendo funções (operações) eoutros valores (atributos).

local Q = {head = 0 ,t a i l = 0 ,

}function Q: enqueue ( va l ) −−=> Q. enqueue = f u n c t i o n ( s e l f , va l )

s e l f . t a i l = s e l f . t a i l + 1s e l f [ s e l f . t a i l ] = va l

endfunction Q: dequeue ( ) −−=> Q. dequeue = f u n c t i o n ( s e l f )

i f s e l f . head < s e l f . t a i l thens e l f . head = s e l f . head + 1return s e l f [ s e l f . head ]

endend

Q: enqueue ( " f i r s t " ) −−=> Q. enqueue (Q, " f i r s t " )Q: enqueue ( " second " )Q: enqueue ( " t h i r d " )p r i n t (Q: dequeue ( ) ) −−> f i r s tp r i n t (Q: dequeue ( ) ) −−> second

Page 25: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Construtores

I Uso de funções para validar estruturas.function Book ( i n f o )

asser t ( type ( i n f o ) == " t ab l e " , " i n v a l i d book en t ry " )asser t ( type ( i n f o . t i t l e ) == " s t r i n g " , " i n v a l i d book t i t l e " )asser t ( type ( i n f o . author ) == " s t r i n g " , " i n v a l i d book author " )asser t ( type ( i n f o . year ) == " number " , " i n v a l i d book year " )i f i n f o . e d i t i o n == n i l then

i n f o . e d i t i o n = 1else

asser t ( type ( i n f o . e d i t i o n ) == " number " , " i n v a l i d book e d i t i o n " )endi n f o . en t r y = " book "return i n f o

end

local PiL = Book {t i t l e = " Programming i n Lua " ,author = " Roberto Ie rusa l imschy " ,e d i t i o n = 2 ,year = 2006 ,

}

Page 26: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Construtores

I Uso de funções para construir objetos.

function Queue ( )local data = { }local head = 0local t a i l = 0return {

enqueue = function ( va l )t a i l = t a i l + 1data [ t a i l ] = va l

end ,dequeue = function ( )

i f head < t a i l thenhead = head + 1return data [ head ]

endend ,

}end

local Q = Queue ( )

Q. enqueue ( " f i r s t " )Q. enqueue ( " second " )p r i n t (Q. dequeue ( ) ) −−> f i r s tp r i n t (Q. dequeue ( ) ) −−> second

p r i n t (Q. head ) −−> n i lp r i n t (Q. t a i l ) −−> n i lp r i n t (Q. data ) −−> n i l

Page 27: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Construtores

I Uso de funções para construir objetos.

function Queue ( )local data = { }local head = 0local t a i l = 0return {

enqueue = function ( va l )t a i l = t a i l + 1data [ t a i l ] = va l

end ,dequeue = function ( )

i f head < t a i l thenhead = head + 1return data [ head ]

endend ,

}end

local Q = Queue ( )Q. enqueue ( " f i r s t " )p r i n t (Q. head ) −−> n i l

local function enqueue ( s e l f , va l )s e l f . t a i l = s e l f . t a i l + 1s e l f . data [ s e l f . t a i l ] = va l

endlocal function dequeue ( s e l f )

i f s e l f . head < s e l f . t a i l thens e l f . head = s e l f . head + 1return s e l f . data [ s e l f . head ]

endendfunction Queue ( )

return {head=0 , t a i l =0 , data = { } ,enqueue = enqueue ,dequeue = dequeue ,

}end

local Q = Queue ( )Q: enqueue ( " f i r s t " )p r i n t (Q. head ) −−> 0

Page 28: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Meta-tabelas

I São tabelas contendo campos especiais que estendem ocomportamento de valores em Lua.

function Memoize ( func )local metatable = {

__index = function ( s e l f , key )local value = func ( key )s e l f [ key ] = valuereturn value

end ,}local t ab l e = { }setmetatab le ( tab le , metatable )return t ab l e

end

local s q r t = Memoize ( math . s q r t )p r i n t ( s q r t [ 1 2 1 ] ) −−> 11p r i n t ( s q r t [ 1024 ] ) −−> 32

Page 29: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Prototipação

I Compartilhando membros de outro objeto.John = { name = " John Doe" }function John : show ( )

p r i n t ( " Hi , I ’m a " . . s e l f . name)endJohn : show ( ) −−> Hi , I ’m a John Doe

function clone ( pro to )local ProtoL ike = { __index = pro to }return setmetatab le ( { } , Pro toL ike )

end

guy = clone ( John )guy . name = " guy l i k e John "guy : show ( ) −−> Hi , I ’m a guy l i k e John

Page 30: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Classes

I Fica como exercício. ©I Como definir um conjunto de membros que deve ser

compartilhado por todos os objetos de uma classe?I Como definir uma forma de criar objetos iniciando seus

membros?I Como criar hierarquias de classe de forma que uma herde

(compartilhe) os membros definidos por outra?

Page 31: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Co-Rotinas

I É uma linha de execução com seu próprio contexto(e.g. contador de programa, pilha, variáveis locais, etc.).

local co = corou t ine . c reate ( function ( s t a r t )local cu r ren t = s t a r tlocal commandrepeat

command, arg = corou t ine . y i e l d ( cu r ren t )i f command == "+ " then cu r ren t = cu r ren t + arge l s e i f command == "−" then cu r ren t = cu r ren t − arge l s e i f command ~= "= " then e r r o r ( " bad op " )end

u n t i l command == n i lreturn cu r ren t

end )

p r i n t ( co rou t ine . resume ( co , 5 ) ) −−> t rue 5p r i n t ( co rou t ine . resume ( co , "+ " , 2 ) ) −−> t rue 7p r i n t ( co rou t ine . resume ( co , "+ " , 3 ) ) −−> t rue 10p r i n t ( co rou t ine . resume ( co , "−" , 5 ) ) −−> t rue 5p r i n t ( co rou t ine . resume ( co , "∗ " , 2 ) ) −−> f a l s e . . . : 9 : bad opp r i n t ( co rou t ine . resume ( co , "= " ) ) −−> f a l s e cannot resume dead corou t ine

Page 32: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Co-Rotinas como Iteradores

I Gedar todas as permutações de uma sequência.

local function permgen ( a , n )i f n == 0 then−− produz uma permutaçãocorou t ine . y i e l d ( a )

elsefor i =1 ,n do

a [ n ] , a [ i ] = a [ i ] , a [ n ]permgen ( a , n−1)a [ n ] , a [ i ] = a [ i ] , a [ n ]

endend

end

function perm ( a )return corou t ine . wrap ( function ( )

permgen ( a , #a )end )

end

for p in perm ( { " a " , " b " , " c " } ) dop r i n t ( unpack ( p ) )

end

−−> b c a−−> c b a−−> c a b−−> a c b−−> b a c−−> a b c

Page 33: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Considerações Finais

I O que atrai os usuários atuais de Lua:I Alta portabilidade.I Eficiência e tamanho.I Facilidade para descrição de dados.I Integração fácil com outras linguagens.I Extensibilidade.

I Outros pontos marcantes de Lua.I Implementação da máquina virtual.I Implementação de JIT.I Resgate do conceito de co-rotinas.

I Comunidade de Lua.I Relativamente pequena, mas crescendo.I Bastante técnica.I Muito amigável.

Page 34: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Fim

http://www.lua.org/

Page 35: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Classes

I Há muitos modelos e formas diferentes de fazer. Um ex.:function c lass (members )

members . __index = membersreturn members

end

JohnClass = c lass ( John )

function JohnClass : _ _ t o s t r i n g ( )return s e l f . name

end

myJohn = setmetatab le ( { } , JohnClass )myJohn : show ( ) −−> Hi , I ’m a John Doep r i n t ( myJohn ) −−> John Doe

Page 36: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Classes

I E herança simples?BigJohnClass = c lass ( c lone ( JohnClass ) )

function BigJohnClass : show ( )p r i n t ( " Hi , I ’m a big " . . s e l f . name)

end

myBigJohn = setmetatab le ( { } , BigJohnClass )myBigJohn : show ( ) −−> Hi , I ’m a b ig John Doep r i n t ( myBigJohn ) −−> tab le : 0x102ee0

I E herança múltipla?I Fica como exercício. ©I Dica: use uma função no campo __index.

Page 37: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Classes

I E o construtor?function new( class , . . . )

local ob jec t = setmetatab le ( { } , c lass )i f type ( ob jec t . i n i t ) == " f u n c t i o n " then

ob jec t : i n i t ( . . . )endreturn ob jec t

end

NamedJohnClass = c lass ( c lone ( JohnClass ) )function NamedJohnClass : i n i t (name)

s e l f . name = " John " . . nameend

myJohnSmith = new( NamedJohnClass , " Smith " )myJohnSmith : show ( ) −−> Hi , I ’m a John Smith

Page 38: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Tabelas Fracas

I Atributos privados.WeakKeys = { __mode = " k " }SecretAgentJohnClass = c lass ( clone ( JohnClass ) )do

local Al iasOf = new(WeakKeys )local SecretOf = new(WeakKeys )function SecretAgentJohnClass : i n i t ( a l i as , sec re t )

A l iasOf [ s e l f ] = a l i a sSecretOf [ s e l f ] = secre t

endfunction SecretAgentJohnClass : t e l lme (name)

i f name == Al iasOf [ s e l f ] then return SecretOf [ s e l f ]e l s e i f name == s e l f . name then return " I ’m a " . . s e l f . nameelse return " I ’m not " . . nameend

endend

myAgent = new( SecretAgentJohnClass , "Bond , John Bond" ," Lua i s as much OO as you want i t to be " )

p r i n t ( myAgent : t e l lme ( " John Doe" ) ) −−> I ’m a John Doep r i n t ( myAgent : t e l lme ( "Bond , John Bond" ) ) −−> Lua i s as much OO as you want i t to be

Page 39: Lua 5.1 para Programadores - WordPress.comPequena Fontes em torno de 17 mil linhas de código C. Interpretador+bibliotecas == 153KB (Linux). Rápida “Lua code tends to be executed

Multithread Cooperativo

local threads = {co rou t ine . c reate ( function ( )

for i =1 , 3 dothreads [# threads +1] = corou t ine . c reate ( function ( )

for step =1 , 3 dop r i n t ( s t r i n g . format ( "%s : step %d of 3 " , name . . i , s tep ) )co rou t ine . y i e l d ( )

endend )

endend ) ,

}while # threads > 0 do

local i = 1repeat

local thread = threads [ i ]co rou t ine . resume ( thread )i f corou t ine . s ta tus ( thread ) == " dead " then

t ab l e . remove ( threads , i )else

i = i + 1end

u n t i l i > # threadsend