Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma...
Transcript of Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma...
![Page 1: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/1.jpg)
Lua + Löve
![Page 2: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/2.jpg)
Lua
• mais uma linguagem dinâmica
• alguma similaridade com Python, Perl, e outras
• linguagem de descrição de dados
• ênfase em scripting
• comunicação inter-linguagens
![Page 3: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/3.jpg)
dinamismo
• tipagem dinâmica
• verificações em tempo de execução: valores têm tipo
• tipagem forte: linguagem não aplica operações a tipos incorretos
• interpretação dinâmica de código
• linguagem capaz de interpretar código dinamicamente no mesmo ambiente de execução do programa
![Page 4: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/4.jpg)
como usar Lua
• stand alone X embutida em algum programa
• www.lua.org
![Page 5: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/5.jpg)
usando o interpretador
$ lua -e "print(2^0.5)"
$ lua nome-do-arquivo
$ lua> print(2^0.5)
$ lua > dofile("nome-do-arquivo")
![Page 6: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/6.jpg)
tipos
• number
• string
• boolean
• nil
• function
• table
• thread
• userdata
![Page 7: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/7.jpg)
number
• double
• int
![Page 8: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/8.jpg)
Boolean
• sem exclusividade em testes
• operadores booleanos operam sobre todos os tipos
• nil e false testam como negativos
print (0 or 6)print (nil or 10)print (x or 1)
![Page 9: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/9.jpg)
exemplos
![Page 10: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/10.jpg)
soma elementos array
function add (a)local sum = 0for i = 1, #a do
sum = sum + a[i] endreturn sum
end
print(add({10, 20, 30.5, -9.8}))
![Page 11: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/11.jpg)
soma elementos array
function add (a)local sum = 0for i = 1, #a do
sum = sum + a[i] endreturn sum
end
print(add({10, 20, 30.5, -9.8}))
![Page 12: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/12.jpg)
soma elementos array
function add (a)local sum = 0for i = 1, #a do
sum = sum + a[i] endreturn sum
end
print(add({10, 20, 30.5, -9.8}))
![Page 13: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/13.jpg)
soma linhas de arquivo
function addfile (filenamelocal sum = 0for line in io.lines(filename) do
sum = sum + tonumber(line)endreturn sum
end
![Page 14: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/14.jpg)
io
io.read – padrões: "*a" reads the whole file "*l" reads the next line (without newline) "*L" reads the next line (with newline) "*n" reads a number num reads a string with up to num characters
![Page 15: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/15.jpg)
Funções em Lua
• funções são valores dinâmicos de primeira classe
(function (a, b) print (a+b) end) (10, 20)
table.sort(t, function (a,b) return a.key < b.key
end))
![Page 16: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/16.jpg)
Funções e variáveis
• usamos a sinaxe convencional para armazenar fçs em variáveis
inc = function (a) return a+1 end
function inc (a)return a+1
end
![Page 17: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/17.jpg)
Múltiplos retornos
• funções em Lua podem retornar múltiplos valores
• atribuição múltipla e ajuste de valores
![Page 18: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/18.jpg)
Escopo
• variáveis locais e globais
local a = 5 print(a) --> 5 do local a = 6 -- create a new local inside the do blockprint(a) --> 6
end print(a) --> 5
![Page 19: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/19.jpg)
Escopo léxico e closures
local function f()local v = 0return function ()local val = v
v = v+1 return val
end end
cont1, cont2 = f(), f() print(cont1())print(cont1())print(cont2())print(cont1())print(cont1())print(cont2())
![Page 20: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/20.jpg)
Regiões geométricas
• a função abaixo cria regiões circulares:
function circle (cx, cy, r)return function (x, y)
return (x - cx)^2 + (y - cy)^2 <= r^2end
end
c1 = circle(5.0, -3.2, 4.5)c2 = circle(0, 0, 1)
![Page 21: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/21.jpg)
Combinando regiões
function union (r1, r2)return function (x, y)
return r1(x, y) or r2(x, y)end
end
function inter (r1, r2)return function (x, y)
return r1(x, y) and r2(x, y)end
end
![Page 22: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/22.jpg)
Tabelas
• única forma de estruturar dados em Lua
• arrays, structs, estruturas de dados, …
• ”arrays associativos”: podem ser indexados por valores de quaisquer tipos
![Page 23: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/23.jpg)
{}{x = 5, y = 10}{“Sun”, “Mon”, “Tue”}{[exp1] = exp2, [exp3] = exp4}
Construtores
• criação e inicialização de tabelas
![Page 24: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/24.jpg)
Todos os prefixos de uma string
function prefixes (s, len)len = len or 0if len <= #s then
return string.sub(s, 1, len),prefixes(s, len + 1)
endend
print(prefixes("alo")) --> a al alot = {prefixes("vazavaza")}
![Page 25: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/25.jpg)
Estruturas de Dados (2)
• Arrays: inteiros como índices
• Conjuntos: elementos como índices
a = {}for i=1,n do a[i] = 0 endprint(#a)
t = {}t[x] = true -- t = t ∪ {x}if t[x] then -- x ∈ t?...
![Page 26: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/26.jpg)
Listas Encadeadas
• Tabelas são objetos, criados dinamicamente
list
value - vnext -
old list...
list = {value=v, next=list}
![Page 27: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/27.jpg)
percurso de tabelas
• arrays: ipairs
• outras tabelas: pairs
nt = {}for k, v in pairs(t) dont[v] = k
end
![Page 28: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/28.jpg)
Objetos
• funções de 1a classe + tabelas ≈ objetos
Rectangle = {w = 100, h = 250}
function Rectangle.area ()return Rectangle.w * Rectangle.h
end
function Rectangle.area (self)return self.w * self.h
end
![Page 29: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/29.jpg)
Chamada de métodos
• açucar sintático para métodos
• cuida de self
function a:foo (x)...
end
a.foo = function (self,x)...
end
a:foo(x) a.foo(a,x)
![Page 30: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/30.jpg)
löve
• framework para jogos 2D
• Linux, Windows, MacOS, Android, iOS
• love2d.org
![Page 31: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/31.jpg)
löve – estrutura do jogo
• love.load
• love.update
• love.draw
![Page 32: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/32.jpg)
löve: exemplo bobo
function love.load()text = "hello!"image = love.graphics.newImage( "alter.jpg" )x = 50 y = 200
end
function love.update (dt)x = x + 50*dtif x > 300 then x=50 end
end
function love.draw ()love.graphics.draw(image, x, y, 0, 0.1, 0.1)love.graphics.print(text, x, y-50)
end
![Page 33: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/33.jpg)
interação com eventos
• testes no loop como no arduino
• testes:
function love.update (dt)x = x + 50*dtif love.keyboard.isDown("down") then
y = y + 10end
end
• mas também callbacks para eventos discretos
love.keypressed (key)
![Page 34: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/34.jpg)
löve: interaçãofunction love.load()
x = 50 y = 200w = 200 h = 150
end
function naimagem (mx, my, x, y)return (mx>x) and (mx<x+w) and (my>y) and (my<y+h)
end
function love.keypressed(key)local mx, my = love.mouse.getPosition()if key == 'b' and naimagem (mx,my, x, y) then
y = 200 end
end
function love.update (dt)...
![Page 35: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/35.jpg)
löve: interaçãofunction love.load()
x = 50 y = 200 w = 200 h = 150end
...function love.keypressed(key)
... end
function love.update (dt)local mx, my = love.mouse.getPosition()if love.keyboard.isDown("down") and naimagem(mx, my, x, y) theny = y + 10
end end
function love.draw ()love.graphics.rectangle("line", x, y, w, h)
end
![Page 36: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/36.jpg)
callbacks e estadofunction love.keypressed(key)local mx, my = love.mouse.getPosition()if key == 'b' and naimagem (mx,my, x, y) then
y = 200 end
endfunction love.update (dt)local mx, my = love.mouse.getPosition()if love.keyboard.isDown("down") and naimagem(mx, my, x, y) then
y = y + 10 end
endfunction love.draw ()love.graphics.rectangle("line", x, y, w, h)
end
• variáveis globais capturam estado como no Arduino
• mas podemos usar características da linguagempara encapsular esse estado
![Page 37: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/37.jpg)
encapsulando estadofunction retangulo (x,y,w,h)local originalx, originaly, rx, ry, rw, rh =
x, y, x, y, w, hreturn {
draw = function () love.graphics.rectangle("line", rx, ry, rw, rh)
end, keypressed =function (key)local mx, my = love.mouse.getPosition()...
end } end...function love.load()ret1 = retangulo (50, 200, 200, 150);
end
![Page 38: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/38.jpg)
encapsulando estadofunction retangulo (x,y,w,h)local originalx, originaly, rx, ry, rw, rh =
x, y, x, y, w, hreturn {
draw = function () love.graphics.rectangle("line", rx, ry, rw,
rh)end,
keypressed =function (key)local mx, my = love.mouse.getPosition()...
end } endfunction love.load()ret1 = retangulo (50, 200, 200, 150);
end
![Page 39: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/39.jpg)
encapsulando estadofunction love.load()ret1 = retangulo (50, 200, 200, 150);
end
function love.keypressed(key)ret1.keypressed(key)
end
![Page 40: Lua + Löve - PUC-Rionoemi/sr-19/04-lualove.pdf · Lua •mais uma linguagem dinâmica • alguma similaridade com Python, Perl, e outras •linguagem de descrição de dados •ênfase](https://reader030.fdocumentos.tips/reader030/viewer/2022040608/5ec466ee4e7aca03a87f2cdf/html5/thumbnails/40.jpg)
exercício
1. abrir o ZeroBrane• escolher "project"-> "lua interpreter"-> löve
2. executar código em• sr-19/code/lovelua/retangulo1/main.lua("executar" o diretorio que contém a main.lua)
3. retirar chamada a love.keyboard.isDown e programar a reação à tecla”down” dentro de keypressed – ver o que muda!
4. incluir reação a tecla ”right”,andando com retângulo para a direita5. encapsular o retângulo como indicado em slides "encapsulando estado" –
Agora keypressed e update devem chamar chamar fçs ”keypressed” e ”update” do retângulo
6. criar dois retângulos em sua aplicação, em posições diferentes7. criar um array de retângulos