SlideShare a Scribd company logo
1 of 67
Download to read offline
Lua
Topics
• History + background
• Key features
• Syntax
• Tables
• Embedding
• Usecase
Topics
• History + background
• Key features           Pictures

• Syntax                   Code
• Tables
• Embedding
• Usecase
1977-1992
 Trade Barriers
Pontifícia Universidade
  Católica do Rio de
         Janeiro
PUC
SOL (Simple Object Language)
             +
 DEL (Data Entry Language)
             =
            Lua
Sol
Lua
• Easy to write and understand (so no Lisp,
  TCL or Scheme), Python wasn’t good
  enough yet

• Diverse collection of computers (so highly
  portable, not -nix only)

• Should be provided as a library with a C-
  API
Influences
• Scheme
• Modula
• CLU
• C++
• SNOBOL
• AWK
in use by
etc.
Robust
Fast
Portable
Embeddable
Powerful (yet simple)
Small
Free
Awesome
Syntax
if/then

if true == false then
     print "foobar";
else
     print "Ponies";
end
while

while true do
    print "Ponies!";
end
repeat/until

repeat
    line = os.read()
until line ~= ""
print "Ponies";
Types

print(type("Ponies"))   -->   string
print(type(10.4*3))     -->   number
print(type(print))      -->   function
print(type(type))       -->   function
print(type(true))       -->   boolean
print(type(nil))        -->   nil
print(type(type(X)))    -->   string
Types

print(type(a))    --> nil
a = 10
print(type(a))    --> number
a = "Ponies!!"
print(type(a))    --> string
a = print         -- yes, this is valid!
a(type(a))        --> function
More

• ~= == !=
• ‘local’ for local variables (garbage
  collection)
• bytecode execution on Lua VM (.luac)
Tables
Tables
Functions
   Functions are anonymous, and are pointers
   to variables


a = {p = print}    -- create a table
a.p("Ponies!")     --> Ponies!
print = math.sin   -- `print' now refers to the 'sin' function
a.p(print(1))      --> 0.841470
sin = a.p          -- `sin' now refers to the print function
sin(10, 20)        --> 10       20
Tables

• Can be used to define anything you want
• Classes, objects, namespaces, you name it
• The only complex data structure available
Tables
                           As array

a = {}                -- create a table and reference it in 'a'
k = "x"
a[k] = 10             -- new entry, with key="x" and value=10
a[20] = "Ponies!!1"   -- new entry, key=20 and value="Ponies!!1"
print(a["x"])         --> 10
k = 20
print(a[k])           --> "Ponies!!1"
a["x"] = a["x"] + 1   -- increments entry "x"
print(a["x"])         --> 11
print(a.x)            --> 11
Tables
           As structures (objects)


point = { x = 10, y = 20 }   -- Create new table
print(point["x"])            -- Prints 10
print(point.x)               -- Prints 10
Tables
        As namespace


Point = {}
Point.new =   function (x, y)
  return {x   = x, y = y}
end
Point.set_x   = function (point, x)
  point.x =   x
end
MetaTables!

•   The power to override events on tables, built into
    the interpreter

•   Useful for namespacing, classes, inheritance, etc.
MetaTables!
t1 = {a = "Ponies!"}     --   t1   is   a table with one name-value pair.
t2 = {}                  --   t2   is   an empty table.
setmetatable(t1, t2)     --   t2   is   t1's metatable.
t3 = {c = "Rainbows!"}   --   t3   is   just another table like t1.

t2.__index = t3          -- when a lookup fails in t1, t2 will
                         -- look for a value in t3.

print(t1.a)              -- Ponies!
print(t1.b)              -- nil
print(t1.c)              -- Rainbows!
MetaTables!
                         Another example


t1 = {a = "Ponies!"}     --   t1   is   a table with one name-value pair.
t2 = {}                  --   t2   is   an empty table.
setmetatable(t1, t2)     --   t2   is   t1's metatable.
t3 = {c = "Rainbows!"}   --   t3   is   just another table like t1.

t2.__index = function (t, k)
    return k           -- When no value is found, return the key
end

print(t1.a)              -- Ponies!
print(t1.b)              -- b
print(t1.c)              -- c
Embedding
Python example
                       PyLux

import pylux

# Shorthand to run a Lua script with "lux('script')"
def lux(script):
    pylux.eval("gv", "dostring", script)

# Shorthand to define a Python proc as callback for Lua
def luxcb(name,func):
    pylux.eval("gvc", "setglobal", name, func)

luxGlobals=[]
luxcb("luxAppend", luxGlobals.append)
lux("""
  for i,v in globals() do
     luxAppend(i)
  end
""")
luxGlobals.sort()
print luxGlobals
Ruby example
                   rubyluabridge et all


require 'rubyluabridge'
l = Lua::State.new         # Create a new state for the bridge
                           # (this is your 'sandbox')

l.eval("return 1")         # 1
l.n = 5
l.eval("return n")         # 5
l.eval("s='Ponies!'")
print l.s                  # Ponies!
Usecase
Background
• Medianetwork
• max 10gbit/s
• Millions of request/day (10 million+)
• Only binary data
• Custom solution built in CProxy (old)
• Needed new feature set
• API with several subsystems
Background

• Needed easy maintenance
• Scalable, lightweight, fast
• Future proof
• Features!
• No exposure of backend storage
Decisions

• nginx
• mod_lua
• mod_cache
• mod_proxy
• LuaSockets
Bitmovr.lua

• Lua
• Memcached
• Supports only GET
• Proxy
• Using filesinks => bitmovr
Architecture

                             Loadbalancer




                     lighttpd                edge
                        lighttpd
                           lighttpd
                              lighttpd
                                 lighttpd
                                    lighttpd
                                       nginx




      Loadbalancer




  MediaTool                                         Castor
LuaSocket
-- include libraries
socket = require("socket");

-- create a TCP socket and bind it to the local host at the given port
server = assert(socket.bind('0.0.0.0',50000))

-- loop forever waiting for clients
while 1 do

      -- wait for a connection from any client
      local client = server:accept()

      -- make sure we don't block waiting for this client's line
      client:settimeout(10)

      -- receive the line
      local line, err = client:receive()

      -- if there was no error, send it back to the client
      if not err then

            -- send the same response as was send
            client:send(line);

            -- close the connection
            client:close()
      end
end
LTN12
Sinks, Pumps, Filters, Chains, etc.




-- load the ltn12 module
local ltn12 = require("ltn12")

-- copy a file
ltn12.pump.all(
  ltn12.source.file(io.open("original.png")),
  ltn12.sink.file(io.open("copy.png"))
)
LTN12
     Sinks, Pumps, Filters, Chains, etc.




local outputSink = socket.sink("close-when-done", client)

local r, c, h = socket.http.request{
    sink = outputSink,
    method = 'GET',
    url = storageLocation,
    redirect = true
}
Conclusion

• Fast, simple, elegant, flexible
• A bit of a hurdle
• Sandboxing is interesting
Questions?

More Related Content

What's hot

Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Lua London Meetup 2013
Lua London Meetup 2013Lua London Meetup 2013
Lua London Meetup 2013Cloudflare
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonMax Klymyshyn
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard LibraryNelson Glauber Leal
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 

What's hot (20)

Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Python
PythonPython
Python
 
Lua London Meetup 2013
Lua London Meetup 2013Lua London Meetup 2013
Lua London Meetup 2013
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 

Viewers also liked

Web development with Lua and Sailor @ GeeCon 2015
Web development with Lua and Sailor @ GeeCon 2015Web development with Lua and Sailor @ GeeCon 2015
Web development with Lua and Sailor @ GeeCon 2015Etiene Dalcol
 
Lua as a business logic language in high load application
Lua as a business logic language in high load applicationLua as a business logic language in high load application
Lua as a business logic language in high load applicationIlya Martynov
 
LuaConf 2016 - Becoming a Lua Powered Super Hero
LuaConf 2016 - Becoming a Lua Powered Super HeroLuaConf 2016 - Becoming a Lua Powered Super Hero
LuaConf 2016 - Becoming a Lua Powered Super HeroCharles McKeever
 

Viewers also liked (6)

What's wrong with web
What's wrong with webWhat's wrong with web
What's wrong with web
 
Web development with Lua and Sailor @ GeeCon 2015
Web development with Lua and Sailor @ GeeCon 2015Web development with Lua and Sailor @ GeeCon 2015
Web development with Lua and Sailor @ GeeCon 2015
 
Lua and its Ecosystem
Lua and its EcosystemLua and its Ecosystem
Lua and its Ecosystem
 
Lua as a business logic language in high load application
Lua as a business logic language in high load applicationLua as a business logic language in high load application
Lua as a business logic language in high load application
 
Lua vs python
Lua vs pythonLua vs python
Lua vs python
 
LuaConf 2016 - Becoming a Lua Powered Super Hero
LuaConf 2016 - Becoming a Lua Powered Super HeroLuaConf 2016 - Becoming a Lua Powered Super Hero
LuaConf 2016 - Becoming a Lua Powered Super Hero
 

Similar to Lua first steps

Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
AutoDesk
AutoDeskAutoDesk
AutoDeskSE3D
 

Similar to Lua first steps (20)

Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Redis Lua Scripts
Redis Lua ScriptsRedis Lua Scripts
Redis Lua Scripts
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
AutoDesk
AutoDeskAutoDesk
AutoDesk
 
N flavors of streaming
N flavors of streamingN flavors of streaming
N flavors of streaming
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Lua first steps

  • 1. Lua
  • 2. Topics • History + background • Key features • Syntax • Tables • Embedding • Usecase
  • 3. Topics • History + background • Key features Pictures • Syntax Code • Tables • Embedding • Usecase
  • 4.
  • 5.
  • 6.
  • 7.
  • 9. Pontifícia Universidade Católica do Rio de Janeiro
  • 10. PUC
  • 11.
  • 12. SOL (Simple Object Language) + DEL (Data Entry Language) = Lua
  • 13. Sol
  • 14. Lua
  • 15. • Easy to write and understand (so no Lisp, TCL or Scheme), Python wasn’t good enough yet • Diverse collection of computers (so highly portable, not -nix only) • Should be provided as a library with a C- API
  • 16. Influences • Scheme • Modula • CLU • C++ • SNOBOL • AWK
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25. etc.
  • 26.
  • 28. Fast
  • 32. Small
  • 33. Free
  • 36. if/then if true == false then print "foobar"; else print "Ponies"; end
  • 37. while while true do print "Ponies!"; end
  • 38. repeat/until repeat line = os.read() until line ~= "" print "Ponies";
  • 39. Types print(type("Ponies")) --> string print(type(10.4*3)) --> number print(type(print)) --> function print(type(type)) --> function print(type(true)) --> boolean print(type(nil)) --> nil print(type(type(X))) --> string
  • 40. Types print(type(a)) --> nil a = 10 print(type(a)) --> number a = "Ponies!!" print(type(a)) --> string a = print -- yes, this is valid! a(type(a)) --> function
  • 41. More • ~= == != • ‘local’ for local variables (garbage collection) • bytecode execution on Lua VM (.luac)
  • 44. Functions Functions are anonymous, and are pointers to variables a = {p = print} -- create a table a.p("Ponies!") --> Ponies! print = math.sin -- `print' now refers to the 'sin' function a.p(print(1)) --> 0.841470 sin = a.p -- `sin' now refers to the print function sin(10, 20) --> 10 20
  • 45. Tables • Can be used to define anything you want • Classes, objects, namespaces, you name it • The only complex data structure available
  • 46. Tables As array a = {} -- create a table and reference it in 'a' k = "x" a[k] = 10 -- new entry, with key="x" and value=10 a[20] = "Ponies!!1" -- new entry, key=20 and value="Ponies!!1" print(a["x"]) --> 10 k = 20 print(a[k]) --> "Ponies!!1" a["x"] = a["x"] + 1 -- increments entry "x" print(a["x"]) --> 11 print(a.x) --> 11
  • 47. Tables As structures (objects) point = { x = 10, y = 20 } -- Create new table print(point["x"]) -- Prints 10 print(point.x) -- Prints 10
  • 48. Tables As namespace Point = {} Point.new = function (x, y) return {x = x, y = y} end Point.set_x = function (point, x) point.x = x end
  • 49. MetaTables! • The power to override events on tables, built into the interpreter • Useful for namespacing, classes, inheritance, etc.
  • 50. MetaTables! t1 = {a = "Ponies!"} -- t1 is a table with one name-value pair. t2 = {} -- t2 is an empty table. setmetatable(t1, t2) -- t2 is t1's metatable. t3 = {c = "Rainbows!"} -- t3 is just another table like t1. t2.__index = t3 -- when a lookup fails in t1, t2 will -- look for a value in t3. print(t1.a) -- Ponies! print(t1.b) -- nil print(t1.c) -- Rainbows!
  • 51. MetaTables! Another example t1 = {a = "Ponies!"} -- t1 is a table with one name-value pair. t2 = {} -- t2 is an empty table. setmetatable(t1, t2) -- t2 is t1's metatable. t3 = {c = "Rainbows!"} -- t3 is just another table like t1. t2.__index = function (t, k) return k -- When no value is found, return the key end print(t1.a) -- Ponies! print(t1.b) -- b print(t1.c) -- c
  • 53. Python example PyLux import pylux # Shorthand to run a Lua script with "lux('script')" def lux(script): pylux.eval("gv", "dostring", script) # Shorthand to define a Python proc as callback for Lua def luxcb(name,func): pylux.eval("gvc", "setglobal", name, func) luxGlobals=[] luxcb("luxAppend", luxGlobals.append) lux(""" for i,v in globals() do luxAppend(i) end """) luxGlobals.sort() print luxGlobals
  • 54. Ruby example rubyluabridge et all require 'rubyluabridge' l = Lua::State.new # Create a new state for the bridge # (this is your 'sandbox') l.eval("return 1") # 1 l.n = 5 l.eval("return n") # 5 l.eval("s='Ponies!'") print l.s # Ponies!
  • 56. Background • Medianetwork • max 10gbit/s • Millions of request/day (10 million+) • Only binary data • Custom solution built in CProxy (old) • Needed new feature set • API with several subsystems
  • 57. Background • Needed easy maintenance • Scalable, lightweight, fast • Future proof • Features! • No exposure of backend storage
  • 58. Decisions • nginx • mod_lua • mod_cache • mod_proxy • LuaSockets
  • 59. Bitmovr.lua • Lua • Memcached • Supports only GET • Proxy • Using filesinks => bitmovr
  • 60. Architecture Loadbalancer lighttpd edge lighttpd lighttpd lighttpd lighttpd lighttpd nginx Loadbalancer MediaTool Castor
  • 61.
  • 62.
  • 63. LuaSocket -- include libraries socket = require("socket"); -- create a TCP socket and bind it to the local host at the given port server = assert(socket.bind('0.0.0.0',50000)) -- loop forever waiting for clients while 1 do -- wait for a connection from any client local client = server:accept() -- make sure we don't block waiting for this client's line client:settimeout(10) -- receive the line local line, err = client:receive() -- if there was no error, send it back to the client if not err then -- send the same response as was send client:send(line); -- close the connection client:close() end end
  • 64. LTN12 Sinks, Pumps, Filters, Chains, etc. -- load the ltn12 module local ltn12 = require("ltn12") -- copy a file ltn12.pump.all( ltn12.source.file(io.open("original.png")), ltn12.sink.file(io.open("copy.png")) )
  • 65. LTN12 Sinks, Pumps, Filters, Chains, etc. local outputSink = socket.sink("close-when-done", client) local r, c, h = socket.http.request{ sink = outputSink, method = 'GET', url = storageLocation, redirect = true }
  • 66. Conclusion • Fast, simple, elegant, flexible • A bit of a hurdle • Sandboxing is interesting