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

Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask PresentationParag Mujumdar
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And MiddlewareBen Schwarz
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!Kent Chen
 
Cargo makeを使ってみた話
Cargo makeを使ってみた話Cargo makeを使ってみた話
Cargo makeを使ってみた話emakryo
 
Overview of Apache Flink: Next-Gen Big Data Analytics Framework
Overview of Apache Flink: Next-Gen Big Data Analytics FrameworkOverview of Apache Flink: Next-Gen Big Data Analytics Framework
Overview of Apache Flink: Next-Gen Big Data Analytics FrameworkSlim Baltagi
 
Introduction to Ionic framework
Introduction to Ionic frameworkIntroduction to Ionic framework
Introduction to Ionic frameworkShyjal Raazi
 
Building RESTful APIs w/ Grape
Building RESTful APIs w/ GrapeBuilding RESTful APIs w/ Grape
Building RESTful APIs w/ GrapeDaniel Doubrovkine
 
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミング
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミングJavaからScala、そしてClojureへ: 実務で活きる関数型プログラミング
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミングKent Ohashi
 
はじめようGit
はじめようGitはじめようGit
はじめようGittechscore
 
"허니몬의 마크다운 사용기"
"허니몬의 마크다운 사용기""허니몬의 마크다운 사용기"
"허니몬의 마크다운 사용기"Ji Heon Kim
 
Webブラウザ上で動作する帳票エンジンを作る話
Webブラウザ上で動作する帳票エンジンを作る話Webブラウザ上で動作する帳票エンジンを作る話
Webブラウザ上で動作する帳票エンジンを作る話terurou
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 
Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)
 Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編) Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)
Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)Hiroshi Tokumaru
 
Redmineプラグイン導入・開発入門
Redmineプラグイン導入・開発入門Redmineプラグイン導入・開発入門
Redmineプラグイン導入・開発入門Minoru Maeda
 

What's hot (20)

Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
GDB Rocks!
GDB Rocks!GDB Rocks!
GDB Rocks!
 
Spring Batch Introduction
Spring Batch IntroductionSpring Batch Introduction
Spring Batch Introduction
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And Middleware
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!Working Remotely (via SSH) Rocks!
Working Remotely (via SSH) Rocks!
 
Cargo makeを使ってみた話
Cargo makeを使ってみた話Cargo makeを使ってみた話
Cargo makeを使ってみた話
 
Overview of Apache Flink: Next-Gen Big Data Analytics Framework
Overview of Apache Flink: Next-Gen Big Data Analytics FrameworkOverview of Apache Flink: Next-Gen Big Data Analytics Framework
Overview of Apache Flink: Next-Gen Big Data Analytics Framework
 
Introduction to Ionic framework
Introduction to Ionic frameworkIntroduction to Ionic framework
Introduction to Ionic framework
 
Building RESTful APIs w/ Grape
Building RESTful APIs w/ GrapeBuilding RESTful APIs w/ Grape
Building RESTful APIs w/ Grape
 
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミング
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミングJavaからScala、そしてClojureへ: 実務で活きる関数型プログラミング
JavaからScala、そしてClojureへ: 実務で活きる関数型プログラミング
 
はじめようGit
はじめようGitはじめようGit
はじめようGit
 
Vim Rocks!
Vim Rocks!Vim Rocks!
Vim Rocks!
 
"허니몬의 마크다운 사용기"
"허니몬의 마크다운 사용기""허니몬의 마크다운 사용기"
"허니몬의 마크다운 사용기"
 
Webブラウザ上で動作する帳票エンジンを作る話
Webブラウザ上で動作する帳票エンジンを作る話Webブラウザ上で動作する帳票エンジンを作る話
Webブラウザ上で動作する帳票エンジンを作る話
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
Flask
FlaskFlask
Flask
 
Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)
 Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編) Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)
Webサイトをめぐるセキュリティ状況と効果的な防御方法(WordPress編)
 
Redmineプラグイン導入・開発入門
Redmineプラグイン導入・開発入門Redmineプラグイン導入・開発入門
Redmineプラグイン導入・開発入門
 
gRPC
gRPC gRPC
gRPC
 

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 Apache Spark
Debugging Apache SparkDebugging Apache Spark
Debugging Apache Spark
 
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
 
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

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
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
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
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
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

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