SlideShare a Scribd company logo
1 of 35
Lua: the world’s most infuriating language
October 16, 2013
The simplest way to a safer, faster and smarter website
My background
• Lots of...
• Assembly
• C, C++ and Go
• Perl, Tcl
• LISP (and relations)

• And lately...
• Lua

2
My first Lua program

3
4
The End

5
CHDK on Canon A560

6
CHDK Lua Interface
• Lua’s extensibility means it can control the camera
• http://chdk.wikia.com/wiki/Lua

• Functions added to Lua like
• shoot() – takes a picture
• press(), release() – press the shutter button (allows a partial press)

• get_orientation_sensor() – figure out camera orientation
• get_temperature() – get camera internal temperatures

7
-- Now enter a self-check of the manual mode settings
log( "Self-check started" )
assert_prop( 49, -32764, "Not in manual mode" )
assert_prop( 5,
0, "AF Assist Beam should be Off" )
assert_prop( 6,
0, "Focus Mode should be Normal" )
assert_prop( 8,
0, "AiAF Mode should be On" )
assert_prop( 21,
0, "Auto Rotate should be Off" )
assert_prop( 29,
0, "Bracket Mode should be None" )
assert_prop( 57,
0, "Picture Mode should be Superfine" )
assert_prop( 66,
0, "Date Stamp should be Off" )
assert_prop( 95,
0, "Digital Zoom should be None" )
assert_prop( 102,
0, "Drive Mode should be Single" )
assert_prop( 133,
0, "Manual Focus Mode should be Off" )
assert_prop( 143,
2, "Flash Mode should be Off" )
assert_prop( 149,
100, "ISO Mode should be 100" )
assert_prop( 218,
0, "Picture Size should be L" )
assert_prop( 268,
0, "White Balance Mode should be Auto" )
assert_gt( get_time("Y"), 2009, "Unexpected year" )
assert_gt( get_time("h"), 6, "Hour appears too early" )
assert_lt( get_time("h"), 20, "Hour appears too late" )
assert_gt( get_vbatt(), 3000, "Batteries seem low" )
assert_gt( get_jpg_count(), ns, "Insufficient card space" )
log( "Self-check complete" )

8
https://github.com/jgrahamc/gaga/tree/master/gaga-1/camera
if ( ok == 1 ) then
sleep(s)
log( "Starting picture capture" )
n = 0
while ( 1 ) do
tc = c
while ( tc > 0 ) do
shoot()
n = n + 1
log( string.format("Picture %i taken", n ))
tc = tc - 1
end
log( string.format("Temperatures: %i, %i, %i",
get_temperature(0), get_temperature(1), get_temperature(2) ))
log( string.format("Battery level %i", get_vbatt()))
sleep(i)
end
end
log( "Done" )
9
Initial Irritants
• Seemed awfully verbose (bit like BASIC!)
• if... then... else... end

• Little shortcuts were missing
• x += 1

• p?a:b

• Made it feel like a toy language

10
Irritant: +=
• Happy not to have x++
• But why no +=?

11
Irritant: ternary operator
• Super useful to be able to do

local bird = duck?”It’s a duck”:”Not a duck”
• Can’t.
• Solution is the ugly

local bird = duck and “It’s a duck” or “Not a duck”
• And it’s a bad solution

local thing = question and returnsfalse() or crash()

12
Irritant: not and ~=
• Not equals is ~=
• Which Perl programmers will confuse with =~

if x ~= 5 then print “Not five” end

• But not is not ~ it’s not!

if not x == 5 then print “Not five” end
if ~(x == 5) then print “Not five” end
if not (x == 5) then print “Not five” end

13
Next Lua Program
• Web Application Firewall
• About 2,000 lines of Lua
• Replaced 37,000 line C program!
• Plus 3,000 of automatically generated Lua

• Used by CloudFlare to process HTTP requests
• Checks for XSS, CSRF, SQL injection
• Bad browsers
• Custom rules

• Turns out Lua was great for this!
14
Really, really fast: 1 to 2ms per request

15
LuaJIT

16
LuaJIT FFI

17
Lulip
• Line level profiler for Lua in Lua: https://github.com/jgrahamc/lulip/

local profiler = require 'lulip'
local p = profiler:new()
p:dont('some-module')
p:maxrows(25)
p:start()
-- execute code here
p:stop()
p:dump(output_file_name)

18
Lulip Output

19
Lulip Core
• Nice things
• Lua’s debug library
• LuaJIT’s FFI for gettimeofday()
• Closures

-- start: begin profiling
function start(self)
self:dont('lulip.lua')
self.start_time = gettimeofday()
self.current_line = nil
self.current_start = 0
debug.sethook(function(e,l) self:event(e, l) end, "l")
end

20
Performance Tricks
• Wait til you’ve finished; Measure; Fix the slow things
• Locals way faster than globals

local rand = math.random
local len = #t
for i=1,len do
...
end
• . syntax faster than :

local slen = string.len
s:len() vs. slen(s)
• Minimize closures

21
Autogenerated Code

22
nginx + Lua and OpenResty
• http://wiki.nginx.org/HttpLuaModule
• Control over all phases of nginx inside Lua
• Very fast, very flexible, non-blocking (without callbacks!)
• Sockets, coroutines, subrequests, shared in-memory caching
• http://openresty.org/
• Complete package of nginx, Lua and a set of libraries
• Access to Redis, memcached, MySQL, Postgresql
• JSON parsing, DNS, locks, ...

• CloudFlare HTTP almost entirely nginx + Lua / OpenResty

23
CloudFlare WAF

24
Irritant: Arrays
• Index starts at 1
• # doesn’t do what you think

>
>
3
>
>
4
>
>
2

x = {"a", "b", "c"}
=#x
x = {"a", "b", nil, "c"}
=#x
x = {"a", "b", nil, "c", nil}
=#x

25
Irritant: escape characters
• string.find, string.match
• Lots of special characters just like regular expressions
• Character classes: [a-z], [^a-z], .
• Repetition: *, +, ?
• Anchors: ^ and $
• Groups and alternation: (foo|bar)

• And then... %
• %d, %u, %D, %s

• Although %b and %f are cool

26
Awesome: tables
• Anything can be a key; anything can be a value
• Tables as values for nesting
• Functions as values

x = {“a”, “b”, “c”}
y = {subtable=x, double=function(v) return v*2 end}
• Tables are references

function f(t, v) t.subtable = v end
f(y, {“1”, “2”, “3”})

27
Tables aren’t cool... metatables are cool

28
metatables to make a table read-only
local t = {a = “A”}
local _t = t
t = {}
local ro = {
__index = _t,
__newindex = function() error(“R/O”) end
}
setmetatable(t, ro)

print(t.a)
t.a = “B”

29
metatables for lazy loading
local t = {}
local loader = {
__index=function(_t, _v)
_t[_v] = docostlyload(_v)
return _t[_v]
end}
setmetatable(t, loader)

print(t.expensive)

30
metatables to make objects
local C = {}
C.__index = C
function C.new(d)
local newObject = {data=d}
return setmetatable(newObject, C)
end
function C.get_data(self)
return self.data
end
local o = C.new(“hello”)
print(o:get_data())

31
metatables to sandbox code #1
local env = { print = print }
local envmeta = { __index={}, __newindex=function() end }
setmetatable(env, envmeta)

function run(code)
local f = loadstring(code)
setfenv(f, env)
pcall(f)
end
run([[
local x = “Hello, World!”
print(x)
local y = string.len(x)
]])

32
metatables to sandbox code #2
local env = { print = print, string = { len = string.len } }
local envmeta = { __index={}, __newindex=function() end }
setmetatable(env, envmeta)

function run(code)
local f = loadstring(code)
setfenv(f, env)
pcall(f)
end
run([[
local x = “Hello, World!”
print(x)
local y = string.len(x)
]])

33
metatables for undefined variable detection
function doubler(x) return X*2 end
print(doubler(2))
t.lua:1: attempt to perform arithmetic on global 'X' (a nil value)

function doubler(x) return X*2 end
catcher={__index=function(t,v) error(v .. “ undefined”) end,
__newindex=function(t,k,v) error(v .. “ undefined”) end}
setmetatable(_G, catcher)
print(doubler(2))
lua: t.lua:2: Tried to read undefined X

34
Conclusion
• Get past initial irritation!
• Lua is a GREAT language for embedding in large

systems
• Fast
• Lots of functionality

• Good standard library
• Small
• Extensible both from C and to C

35

More Related Content

What's hot

簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率
簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率
簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率Shengyou Fan
 
Lec 3 knowledge acquisition representation and inference
Lec 3  knowledge acquisition representation and inferenceLec 3  knowledge acquisition representation and inference
Lec 3 knowledge acquisition representation and inferenceEyob Sisay
 
Unit 3 file management
Unit 3 file managementUnit 3 file management
Unit 3 file managementKalai Selvi
 
Windows internals Essentials
Windows internals EssentialsWindows internals Essentials
Windows internals EssentialsJohn Ombagi
 
Parallel Genetic Algorithms in the Cloud
Parallel Genetic Algorithms in the CloudParallel Genetic Algorithms in the Cloud
Parallel Genetic Algorithms in the CloudPasquale Salza
 
Introduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticleIntroduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticlePRIYATHAMDARISI
 
Write Smart Contracts with Truffle Framework
Write Smart Contracts with Truffle FrameworkWrite Smart Contracts with Truffle Framework
Write Smart Contracts with Truffle FrameworkShun Shiku
 
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital ForensicDonghyun Kim
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub ActionsBo-Yi Wu
 
Knowledge representation and reasoning
Knowledge representation and reasoningKnowledge representation and reasoning
Knowledge representation and reasoningMaryam Maleki
 
The Hack Spectrum: Tips, Tricks, and Hacks for Unity
The Hack Spectrum: Tips, Tricks, and Hacks for UnityThe Hack Spectrum: Tips, Tricks, and Hacks for Unity
The Hack Spectrum: Tips, Tricks, and Hacks for UnityRyan Hipple
 
Windbg cmds
Windbg cmdsWindbg cmds
Windbg cmdskewuc
 
Python Programlama Dili
Python Programlama DiliPython Programlama Dili
Python Programlama DiliCihan Özhan
 
An Introduction of SQL Injection, Buffer Overflow & Wireless Attack
An Introduction of SQL Injection, Buffer Overflow & Wireless AttackAn Introduction of SQL Injection, Buffer Overflow & Wireless Attack
An Introduction of SQL Injection, Buffer Overflow & Wireless AttackTechSecIT
 

What's hot (20)

簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率
簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率
簡化 JVM 上雲 - 透過 Azure Spring Cloud 提升開發、發佈及服務監控效率
 
Lec 3 knowledge acquisition representation and inference
Lec 3  knowledge acquisition representation and inferenceLec 3  knowledge acquisition representation and inference
Lec 3 knowledge acquisition representation and inference
 
Knowledge Representation in AI.pptx
Knowledge Representation in AI.pptxKnowledge Representation in AI.pptx
Knowledge Representation in AI.pptx
 
Guide to Open Source Compliance
Guide to Open Source ComplianceGuide to Open Source Compliance
Guide to Open Source Compliance
 
Unit 3 file management
Unit 3 file managementUnit 3 file management
Unit 3 file management
 
Windows internals Essentials
Windows internals EssentialsWindows internals Essentials
Windows internals Essentials
 
Parallel Genetic Algorithms in the Cloud
Parallel Genetic Algorithms in the CloudParallel Genetic Algorithms in the Cloud
Parallel Genetic Algorithms in the Cloud
 
Introduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticleIntroduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech Article
 
Mycin
MycinMycin
Mycin
 
Write Smart Contracts with Truffle Framework
Write Smart Contracts with Truffle FrameworkWrite Smart Contracts with Truffle Framework
Write Smart Contracts with Truffle Framework
 
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
 
Neural network and fuzzy logic
Neural network and fuzzy logicNeural network and fuzzy logic
Neural network and fuzzy logic
 
Knowledge representation and reasoning
Knowledge representation and reasoningKnowledge representation and reasoning
Knowledge representation and reasoning
 
Knowledge representation
Knowledge representationKnowledge representation
Knowledge representation
 
The Hack Spectrum: Tips, Tricks, and Hacks for Unity
The Hack Spectrum: Tips, Tricks, and Hacks for UnityThe Hack Spectrum: Tips, Tricks, and Hacks for Unity
The Hack Spectrum: Tips, Tricks, and Hacks for Unity
 
jBPM, open source BPM
jBPM, open source BPMjBPM, open source BPM
jBPM, open source BPM
 
Windbg cmds
Windbg cmdsWindbg cmds
Windbg cmds
 
Python Programlama Dili
Python Programlama DiliPython Programlama Dili
Python Programlama Dili
 
An Introduction of SQL Injection, Buffer Overflow & Wireless Attack
An Introduction of SQL Injection, Buffer Overflow & Wireless AttackAn Introduction of SQL Injection, Buffer Overflow & Wireless Attack
An Introduction of SQL Injection, Buffer Overflow & Wireless Attack
 

Viewers also liked

HAB Software Woes
HAB Software WoesHAB Software Woes
HAB Software Woesjgrahamc
 
PHP is the King, nodejs is the Prince and Lua is the fool
PHP is the King, nodejs is the Prince and Lua is the foolPHP is the King, nodejs is the Prince and Lua is the fool
PHP is the King, nodejs is the Prince and Lua is the foolAlessandro Cinelli (cirpo)
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summaryHoChul Shin
 
What's new in Redis v3.2
What's new in Redis v3.2What's new in Redis v3.2
What's new in Redis v3.2Itamar Haber
 
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
 
Get started with Lua - Hackference 2016
Get started with Lua - Hackference 2016Get started with Lua - Hackference 2016
Get started with Lua - Hackference 2016Etiene Dalcol
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyAerospike
 
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR Toolkit
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR ToolkitImplemetation of parallelism in HMM DNN based state of the art kaldi ASR Toolkit
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR ToolkitShubham Verma
 
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
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua tableShuai Yuan
 
English Preposition
English PrepositionEnglish Preposition
English Prepositionannasnz19
 
Kaldi-voice: Your personal speech recognition server using open source code
Kaldi-voice: Your personal speech recognition server using open source codeKaldi-voice: Your personal speech recognition server using open source code
Kaldi-voice: Your personal speech recognition server using open source codeXavier Anguera
 

Viewers also liked (20)

HAB Software Woes
HAB Software WoesHAB Software Woes
HAB Software Woes
 
PHP is the King, nodejs is the Prince and Lua is the fool
PHP is the King, nodejs is the Prince and Lua is the foolPHP is the King, nodejs is the Prince and Lua is the fool
PHP is the King, nodejs is the Prince and Lua is the fool
 
Go memory
Go memoryGo memory
Go memory
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summary
 
Lua vs python
Lua vs pythonLua vs python
Lua vs python
 
Rails OO views
Rails OO viewsRails OO views
Rails OO views
 
What's new in Redis v3.2
What's new in Redis v3.2What's new in Redis v3.2
What's new in Redis v3.2
 
Lua first steps
Lua first stepsLua first steps
Lua first steps
 
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
 
Get started with Lua - Hackference 2016
Get started with Lua - Hackference 2016Get started with Lua - Hackference 2016
Get started with Lua - Hackference 2016
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR Toolkit
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR ToolkitImplemetation of parallelism in HMM DNN based state of the art kaldi ASR Toolkit
Implemetation of parallelism in HMM DNN based state of the art kaldi ASR Toolkit
 
Nlp tech talk
Nlp tech talkNlp tech talk
Nlp tech talk
 
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
 
Hands on lua
Hands on luaHands on lua
Hands on lua
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua table
 
English Preposition
English PrepositionEnglish Preposition
English Preposition
 
Kaldi-voice: Your personal speech recognition server using open source code
Kaldi-voice: Your personal speech recognition server using open source codeKaldi-voice: Your personal speech recognition server using open source code
Kaldi-voice: Your personal speech recognition server using open source code
 

Similar to Lua: the world's most infuriating language

Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsRobert Coup
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
AutoDesk
AutoDeskAutoDesk
AutoDeskSE3D
 
Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014SergeyLerg
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014ryanerickson
 
Use of Lua in Lab Devices
Use of Lua in Lab DevicesUse of Lua in Lab Devices
Use of Lua in Lab DevicesClaus Kühnel
 
Pylons + Tokyo Cabinet
Pylons + Tokyo CabinetPylons + Tokyo Cabinet
Pylons + Tokyo CabinetBen Cheng
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackNelson Glauber Leal
 
Intro to Spark - for Denver Big Data Meetup
Intro to Spark - for Denver Big Data MeetupIntro to Spark - for Denver Big Data Meetup
Intro to Spark - for Denver Big Data MeetupGwen (Chen) Shapira
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Big data shim
Big data shimBig data shim
Big data shimtistrue
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensNETWAYS
 
Debugging Spark: Scala and Python - Super Happy Fun Times @ Data Day Texas 2018
Debugging Spark:  Scala and Python - Super Happy Fun Times @ Data Day Texas 2018Debugging Spark:  Scala and Python - Super Happy Fun Times @ Data Day Texas 2018
Debugging Spark: Scala and Python - Super Happy Fun Times @ Data Day Texas 2018Holden Karau
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Yuren Ju
 
ruby2600 - an Atari 2600 emulator written in Ruby
ruby2600 - an Atari 2600 emulator written in Rubyruby2600 - an Atari 2600 emulator written in Ruby
ruby2600 - an Atari 2600 emulator written in RubyCarlos Duarte do Nascimento
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdfssusere19c741
 
Ehsan parallel accelerator-dec2015
Ehsan parallel accelerator-dec2015Ehsan parallel accelerator-dec2015
Ehsan parallel accelerator-dec2015Christian Peel
 

Similar to Lua: the world's most infuriating language (20)

Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
AutoDesk
AutoDeskAutoDesk
AutoDesk
 
Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014
 
Use of Lua in Lab Devices
Use of Lua in Lab DevicesUse of Lua in Lab Devices
Use of Lua in Lab Devices
 
Pylons + Tokyo Cabinet
Pylons + Tokyo CabinetPylons + Tokyo Cabinet
Pylons + Tokyo Cabinet
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
Intro to Spark - for Denver Big Data Meetup
Intro to Spark - for Denver Big Data MeetupIntro to Spark - for Denver Big Data Meetup
Intro to Spark - for Denver Big Data Meetup
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Big data shim
Big data shimBig data shim
Big data shim
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet Mens
 
Debugging Spark: Scala and Python - Super Happy Fun Times @ Data Day Texas 2018
Debugging Spark:  Scala and Python - Super Happy Fun Times @ Data Day Texas 2018Debugging Spark:  Scala and Python - Super Happy Fun Times @ Data Day Texas 2018
Debugging Spark: Scala and Python - Super Happy Fun Times @ Data Day Texas 2018
 
Debugging Apache Spark
Debugging Apache SparkDebugging Apache Spark
Debugging Apache Spark
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)
 
ruby2600 - an Atari 2600 emulator written in Ruby
ruby2600 - an Atari 2600 emulator written in Rubyruby2600 - an Atari 2600 emulator written in Ruby
ruby2600 - an Atari 2600 emulator written in Ruby
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf
 
Ehsan parallel accelerator-dec2015
Ehsan parallel accelerator-dec2015Ehsan parallel accelerator-dec2015
Ehsan parallel accelerator-dec2015
 

More from jgrahamc

Better living through microcontrollers
Better living through microcontrollersBetter living through microcontrollers
Better living through microcontrollersjgrahamc
 
Big O London Meetup April 2015
Big O London Meetup April 2015Big O London Meetup April 2015
Big O London Meetup April 2015jgrahamc
 
Go Containers
Go ContainersGo Containers
Go Containersjgrahamc
 
How to launch and defend against a DDoS
How to launch and defend against a DDoSHow to launch and defend against a DDoS
How to launch and defend against a DDoSjgrahamc
 
Software Debugging for High-altitude Balloons
Software Debugging for High-altitude BalloonsSoftware Debugging for High-altitude Balloons
Software Debugging for High-altitude Balloonsjgrahamc
 
Highlights of Go 1.1
Highlights of Go 1.1Highlights of Go 1.1
Highlights of Go 1.1jgrahamc
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
That'll never work!
That'll never work!That'll never work!
That'll never work!jgrahamc
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Securityjgrahamc
 

More from jgrahamc (9)

Better living through microcontrollers
Better living through microcontrollersBetter living through microcontrollers
Better living through microcontrollers
 
Big O London Meetup April 2015
Big O London Meetup April 2015Big O London Meetup April 2015
Big O London Meetup April 2015
 
Go Containers
Go ContainersGo Containers
Go Containers
 
How to launch and defend against a DDoS
How to launch and defend against a DDoSHow to launch and defend against a DDoS
How to launch and defend against a DDoS
 
Software Debugging for High-altitude Balloons
Software Debugging for High-altitude BalloonsSoftware Debugging for High-altitude Balloons
Software Debugging for High-altitude Balloons
 
Highlights of Go 1.1
Highlights of Go 1.1Highlights of Go 1.1
Highlights of Go 1.1
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
That'll never work!
That'll never work!That'll never work!
That'll never work!
 
Javascript Security
Javascript SecurityJavascript Security
Javascript Security
 

Recently uploaded

"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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

"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...
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
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...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Lua: the world's most infuriating language

  • 1. Lua: the world’s most infuriating language October 16, 2013 The simplest way to a safer, faster and smarter website
  • 2. My background • Lots of... • Assembly • C, C++ and Go • Perl, Tcl • LISP (and relations) • And lately... • Lua 2
  • 3. My first Lua program 3
  • 4. 4
  • 6. CHDK on Canon A560 6
  • 7. CHDK Lua Interface • Lua’s extensibility means it can control the camera • http://chdk.wikia.com/wiki/Lua • Functions added to Lua like • shoot() – takes a picture • press(), release() – press the shutter button (allows a partial press) • get_orientation_sensor() – figure out camera orientation • get_temperature() – get camera internal temperatures 7
  • 8. -- Now enter a self-check of the manual mode settings log( "Self-check started" ) assert_prop( 49, -32764, "Not in manual mode" ) assert_prop( 5, 0, "AF Assist Beam should be Off" ) assert_prop( 6, 0, "Focus Mode should be Normal" ) assert_prop( 8, 0, "AiAF Mode should be On" ) assert_prop( 21, 0, "Auto Rotate should be Off" ) assert_prop( 29, 0, "Bracket Mode should be None" ) assert_prop( 57, 0, "Picture Mode should be Superfine" ) assert_prop( 66, 0, "Date Stamp should be Off" ) assert_prop( 95, 0, "Digital Zoom should be None" ) assert_prop( 102, 0, "Drive Mode should be Single" ) assert_prop( 133, 0, "Manual Focus Mode should be Off" ) assert_prop( 143, 2, "Flash Mode should be Off" ) assert_prop( 149, 100, "ISO Mode should be 100" ) assert_prop( 218, 0, "Picture Size should be L" ) assert_prop( 268, 0, "White Balance Mode should be Auto" ) assert_gt( get_time("Y"), 2009, "Unexpected year" ) assert_gt( get_time("h"), 6, "Hour appears too early" ) assert_lt( get_time("h"), 20, "Hour appears too late" ) assert_gt( get_vbatt(), 3000, "Batteries seem low" ) assert_gt( get_jpg_count(), ns, "Insufficient card space" ) log( "Self-check complete" ) 8
  • 9. https://github.com/jgrahamc/gaga/tree/master/gaga-1/camera if ( ok == 1 ) then sleep(s) log( "Starting picture capture" ) n = 0 while ( 1 ) do tc = c while ( tc > 0 ) do shoot() n = n + 1 log( string.format("Picture %i taken", n )) tc = tc - 1 end log( string.format("Temperatures: %i, %i, %i", get_temperature(0), get_temperature(1), get_temperature(2) )) log( string.format("Battery level %i", get_vbatt())) sleep(i) end end log( "Done" ) 9
  • 10. Initial Irritants • Seemed awfully verbose (bit like BASIC!) • if... then... else... end • Little shortcuts were missing • x += 1 • p?a:b • Made it feel like a toy language 10
  • 11. Irritant: += • Happy not to have x++ • But why no +=? 11
  • 12. Irritant: ternary operator • Super useful to be able to do local bird = duck?”It’s a duck”:”Not a duck” • Can’t. • Solution is the ugly local bird = duck and “It’s a duck” or “Not a duck” • And it’s a bad solution local thing = question and returnsfalse() or crash() 12
  • 13. Irritant: not and ~= • Not equals is ~= • Which Perl programmers will confuse with =~ if x ~= 5 then print “Not five” end • But not is not ~ it’s not! if not x == 5 then print “Not five” end if ~(x == 5) then print “Not five” end if not (x == 5) then print “Not five” end 13
  • 14. Next Lua Program • Web Application Firewall • About 2,000 lines of Lua • Replaced 37,000 line C program! • Plus 3,000 of automatically generated Lua • Used by CloudFlare to process HTTP requests • Checks for XSS, CSRF, SQL injection • Bad browsers • Custom rules • Turns out Lua was great for this! 14
  • 15. Really, really fast: 1 to 2ms per request 15
  • 18. Lulip • Line level profiler for Lua in Lua: https://github.com/jgrahamc/lulip/ local profiler = require 'lulip' local p = profiler:new() p:dont('some-module') p:maxrows(25) p:start() -- execute code here p:stop() p:dump(output_file_name) 18
  • 20. Lulip Core • Nice things • Lua’s debug library • LuaJIT’s FFI for gettimeofday() • Closures -- start: begin profiling function start(self) self:dont('lulip.lua') self.start_time = gettimeofday() self.current_line = nil self.current_start = 0 debug.sethook(function(e,l) self:event(e, l) end, "l") end 20
  • 21. Performance Tricks • Wait til you’ve finished; Measure; Fix the slow things • Locals way faster than globals local rand = math.random local len = #t for i=1,len do ... end • . syntax faster than : local slen = string.len s:len() vs. slen(s) • Minimize closures 21
  • 23. nginx + Lua and OpenResty • http://wiki.nginx.org/HttpLuaModule • Control over all phases of nginx inside Lua • Very fast, very flexible, non-blocking (without callbacks!) • Sockets, coroutines, subrequests, shared in-memory caching • http://openresty.org/ • Complete package of nginx, Lua and a set of libraries • Access to Redis, memcached, MySQL, Postgresql • JSON parsing, DNS, locks, ... • CloudFlare HTTP almost entirely nginx + Lua / OpenResty 23
  • 25. Irritant: Arrays • Index starts at 1 • # doesn’t do what you think > > 3 > > 4 > > 2 x = {"a", "b", "c"} =#x x = {"a", "b", nil, "c"} =#x x = {"a", "b", nil, "c", nil} =#x 25
  • 26. Irritant: escape characters • string.find, string.match • Lots of special characters just like regular expressions • Character classes: [a-z], [^a-z], . • Repetition: *, +, ? • Anchors: ^ and $ • Groups and alternation: (foo|bar) • And then... % • %d, %u, %D, %s • Although %b and %f are cool 26
  • 27. Awesome: tables • Anything can be a key; anything can be a value • Tables as values for nesting • Functions as values x = {“a”, “b”, “c”} y = {subtable=x, double=function(v) return v*2 end} • Tables are references function f(t, v) t.subtable = v end f(y, {“1”, “2”, “3”}) 27
  • 28. Tables aren’t cool... metatables are cool 28
  • 29. metatables to make a table read-only local t = {a = “A”} local _t = t t = {} local ro = { __index = _t, __newindex = function() error(“R/O”) end } setmetatable(t, ro) print(t.a) t.a = “B” 29
  • 30. metatables for lazy loading local t = {} local loader = { __index=function(_t, _v) _t[_v] = docostlyload(_v) return _t[_v] end} setmetatable(t, loader) print(t.expensive) 30
  • 31. metatables to make objects local C = {} C.__index = C function C.new(d) local newObject = {data=d} return setmetatable(newObject, C) end function C.get_data(self) return self.data end local o = C.new(“hello”) print(o:get_data()) 31
  • 32. metatables to sandbox code #1 local env = { print = print } local envmeta = { __index={}, __newindex=function() end } setmetatable(env, envmeta) function run(code) local f = loadstring(code) setfenv(f, env) pcall(f) end run([[ local x = “Hello, World!” print(x) local y = string.len(x) ]]) 32
  • 33. metatables to sandbox code #2 local env = { print = print, string = { len = string.len } } local envmeta = { __index={}, __newindex=function() end } setmetatable(env, envmeta) function run(code) local f = loadstring(code) setfenv(f, env) pcall(f) end run([[ local x = “Hello, World!” print(x) local y = string.len(x) ]]) 33
  • 34. metatables for undefined variable detection function doubler(x) return X*2 end print(doubler(2)) t.lua:1: attempt to perform arithmetic on global 'X' (a nil value) function doubler(x) return X*2 end catcher={__index=function(t,v) error(v .. “ undefined”) end, __newindex=function(t,k,v) error(v .. “ undefined”) end} setmetatable(_G, catcher) print(doubler(2)) lua: t.lua:2: Tried to read undefined X 34
  • 35. Conclusion • Get past initial irritation! • Lua is a GREAT language for embedding in large systems • Fast • Lots of functionality • Good standard library • Small • Extensible both from C and to C 35