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

Mise en place d'un système d'information géographique pour la commune de Tunis
Mise en place d'un système d'information géographique pour la commune de TunisMise en place d'un système d'information géographique pour la commune de Tunis
Mise en place d'un système d'information géographique pour la commune de TunisFiras Mejri
 
Mon Projet Fin d'étude: Conception et développement d'une application de géol...
Mon Projet Fin d'étude: Conception et développement d'une application de géol...Mon Projet Fin d'étude: Conception et développement d'une application de géol...
Mon Projet Fin d'étude: Conception et développement d'une application de géol...rim elaire
 
Soutenance de stage TETRA-SI Martial LIPEB
Soutenance de stage TETRA-SI Martial LIPEBSoutenance de stage TETRA-SI Martial LIPEB
Soutenance de stage TETRA-SI Martial LIPEBMartial Lipeb
 
ERP médical pour la TRANSTU : module de gestion pharmaceutiques
ERP médical pour la TRANSTU : module de gestion pharmaceutiquesERP médical pour la TRANSTU : module de gestion pharmaceutiques
ERP médical pour la TRANSTU : module de gestion pharmaceutiquesMohamed Aziz Chetoui
 
TFE. Conception et réalisation d'une application web mobile touristique. Marg...
TFE. Conception et réalisation d'une application web mobile touristique. Marg...TFE. Conception et réalisation d'une application web mobile touristique. Marg...
TFE. Conception et réalisation d'une application web mobile touristique. Marg...Jonathan Margrève
 
Scénarisation de parcours en FOAD
Scénarisation de parcours en FOADScénarisation de parcours en FOAD
Scénarisation de parcours en FOADEpistema
 
Media Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するMedia Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するAtsushi Tadokoro
 
Objets Connectés (IoT) et Data Science
Objets Connectés (IoT) et Data ScienceObjets Connectés (IoT) et Data Science
Objets Connectés (IoT) et Data ScienceSoft Computing
 
オープンソースで始めるAR/VR開発
オープンソースで始めるAR/VR開発オープンソースで始めるAR/VR開発
オープンソースで始めるAR/VR開発Takashi Yoshinaga
 
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~ 新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~ Wataru Ikeda
 
Introduction à AngularJS
Introduction à AngularJSIntroduction à AngularJS
Introduction à AngularJSAbdoulaye Dieng
 
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】GMO GlobalSign Holdings K.K.
 
Inria | Livre blanc Internet des objets (novembre 2021)
Inria | Livre blanc Internet des objets (novembre 2021)Inria | Livre blanc Internet des objets (novembre 2021)
Inria | Livre blanc Internet des objets (novembre 2021)Inria
 
Présentation de RMI Java
Présentation de RMI JavaPrésentation de RMI Java
Présentation de RMI JavaZakaria Bouazza
 
Présentation du stage echatibi sofian
Présentation du stage echatibi sofianPrésentation du stage echatibi sofian
Présentation du stage echatibi sofianSofiane Echatibi
 
Uml 2 pratique de la modélisation
Uml 2  pratique de la modélisationUml 2  pratique de la modélisation
Uml 2 pratique de la modélisationNassim Amine
 
Rapport projet conception et la réalisation d'une application web gestion des...
Rapport projet conception et la réalisation d'une application web gestion des...Rapport projet conception et la réalisation d'une application web gestion des...
Rapport projet conception et la réalisation d'une application web gestion des...SAAD SARHANI
 
Ingéniérie de la Foad
Ingéniérie de la FoadIngéniérie de la Foad
Ingéniérie de la FoadClerquin Sarah
 

What's hot (20)

Mise en place d'un système d'information géographique pour la commune de Tunis
Mise en place d'un système d'information géographique pour la commune de TunisMise en place d'un système d'information géographique pour la commune de Tunis
Mise en place d'un système d'information géographique pour la commune de Tunis
 
Mon Projet Fin d'étude: Conception et développement d'une application de géol...
Mon Projet Fin d'étude: Conception et développement d'une application de géol...Mon Projet Fin d'étude: Conception et développement d'une application de géol...
Mon Projet Fin d'étude: Conception et développement d'une application de géol...
 
Soutenance de stage TETRA-SI Martial LIPEB
Soutenance de stage TETRA-SI Martial LIPEBSoutenance de stage TETRA-SI Martial LIPEB
Soutenance de stage TETRA-SI Martial LIPEB
 
ERP médical pour la TRANSTU : module de gestion pharmaceutiques
ERP médical pour la TRANSTU : module de gestion pharmaceutiquesERP médical pour la TRANSTU : module de gestion pharmaceutiques
ERP médical pour la TRANSTU : module de gestion pharmaceutiques
 
TFE. Conception et réalisation d'une application web mobile touristique. Marg...
TFE. Conception et réalisation d'une application web mobile touristique. Marg...TFE. Conception et réalisation d'une application web mobile touristique. Marg...
TFE. Conception et réalisation d'une application web mobile touristique. Marg...
 
Scénarisation de parcours en FOAD
Scénarisation de parcours en FOADScénarisation de parcours en FOAD
Scénarisation de parcours en FOAD
 
Mini Projet
Mini Projet Mini Projet
Mini Projet
 
Media Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するMedia Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用する
 
Objets Connectés (IoT) et Data Science
Objets Connectés (IoT) et Data ScienceObjets Connectés (IoT) et Data Science
Objets Connectés (IoT) et Data Science
 
オープンソースで始めるAR/VR開発
オープンソースで始めるAR/VR開発オープンソースで始めるAR/VR開発
オープンソースで始めるAR/VR開発
 
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~ 新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~
新しいエフェクトツール、Niagaraを楽しもう!~Niagara作例のブレイクダウン~
 
Introduction à AngularJS
Introduction à AngularJSIntroduction à AngularJS
Introduction à AngularJS
 
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】
Unityで PhotonCloudを使ってリアルタイム・マルチプレイヤーゲームを作っちゃおう【導入編】
 
PFEs SagemCom
PFEs SagemComPFEs SagemCom
PFEs SagemCom
 
Inria | Livre blanc Internet des objets (novembre 2021)
Inria | Livre blanc Internet des objets (novembre 2021)Inria | Livre blanc Internet des objets (novembre 2021)
Inria | Livre blanc Internet des objets (novembre 2021)
 
Présentation de RMI Java
Présentation de RMI JavaPrésentation de RMI Java
Présentation de RMI Java
 
Présentation du stage echatibi sofian
Présentation du stage echatibi sofianPrésentation du stage echatibi sofian
Présentation du stage echatibi sofian
 
Uml 2 pratique de la modélisation
Uml 2  pratique de la modélisationUml 2  pratique de la modélisation
Uml 2 pratique de la modélisation
 
Rapport projet conception et la réalisation d'une application web gestion des...
Rapport projet conception et la réalisation d'une application web gestion des...Rapport projet conception et la réalisation d'une application web gestion des...
Rapport projet conception et la réalisation d'une application web gestion des...
 
Ingéniérie de la Foad
Ingéniérie de la FoadIngéniérie de la Foad
Ingéniérie de la Foad
 

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

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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 ...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

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