SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
A bridge story
Programming iOS in Lua
Lua Workshop 2016
Jean-Luc Jumpertz
@JLJump
October 14, 2016
CodeFlow
Live Application Development Environment
for iOS, tvOS & macOS
CodeFlow
Live Application Development Environment
for iOS, tvOS & macOS
instant feedback on real devices
native OS SDK
live code live assets
true debugger
Lua language
live storyboards
native project APIs
A Bridge? What for?
Transparent development of iOS code in Lua
Goals of the iOS bridge
• Enable the development of iOS apps in Lua using the native OS SDK

• Make the use of the native SDK feel natural in Lua

• Make it easy for a Swift or ObjC developer to move to Lua

Transparent integration between Lua and iOS
• Not the same objective as some other bridges

• Exposing Lua-specific features to the iOS native world was not in the scope, nor was the
definition of a Swift / ObjC version of the Lua C API.

• Low-level aspects of the native world had to be hidden from the Lua code
The foundations
Dealing with type conversions,
memory management, and threads
Mixing Lua and native types
• Different typing systems

• Lua: typed values; untyped function parameters

• C world: typed variables and parameters; ABI

• Calling native from Lua: convert parameters to the expected types

• Easy for base types, more complex for structured types, objects,
collections…

• Doing this conversion is the first role of a bridge

• Example: expose a struct to Lua

• Pseudo-object with constructor, accessors, … and methods

• Automatic Lua table → struct conversion in function calls
struct CGPoint {
CGFloat x;
CGFloat y;
};
local CGPoint = struct.CGPoint:_structInterface { x = 0.0, y = 0.0 }
local aPoint = struct.CGPoint (100, 50)
aPoint.x = 200
self.view.center = aPoint
-- ...
self.view.center = { x = 150, y = aPoint.y + 20 }
LuaC
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
Object B
+1
Object B
+2
Object B
+1
Object B
+0
Object
A
Create
Object
C
Retain
Object
A
Release
Object
C
Release
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
• Managing objects lifecycle
• A native object passed to the Lua runtime is retained until GC-ed, and released by
its finalizer metamethod
• A Lua value passed to the native world maintains a Lua reference to prevent GC
(luaL_ref) and remove this reference when not used anymore. (luaL_unref)
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
• Managing objects lifecycle
• A native object passed to the Lua runtime is retained until GC-ed, and released by
its finalizer metamethod
• A Lua value passed to the native world maintains a Lua reference to prevent GC
(luaL_ref) and remove this reference when not used anymore. (luaL_unref)
• The retain cycle problem
• It is possible from Lua, to create a retain cycle between native objects
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
• Managing objects lifecycle
• A native object passed to the Lua runtime is retained until GC-ed, and released by
its finalizer metamethod
• A Lua value passed to the native world maintains a Lua reference to prevent GC
(luaL_ref) and remove this reference when not used anymore. (luaL_unref)
• The retain cycle problem
• It is possible from Lua, to create a retain cycle between native objects
Object A
+1
Object B
+1
Making Memory Models Coexist
• Different memory models
• Lua: garbage collector
• ObjC runtime: automatic reference counting
• Managing objects lifecycle
• A native object passed to the Lua runtime is retained until GC-ed, and released by
its finalizer metamethod
• A Lua value passed to the native world maintains a Lua reference to prevent GC
(luaL_ref) and remove this reference when not used anymore. (luaL_unref)
• The retain cycle problem
• It is possible from Lua, to create a retain cycle between native objects
memory leak!
• Weak object references are the solution
• Object reference getters: weakRef and strongRef

• A weak reference become an all-nil object when the referenced object is
deallocated
local weakSelf = self.weakRef
Running Lua in a Threaded World
• Lua runs as a single thread, while the host OS is heavily multi-threaded
• In an iOS app, code execution is triggered by user or external events

We can not control in which thread our Lua methods are called!
• The iOS bridge has to make Lua work in a multi-threaded environment
Running Lua in a Threaded World
• Lua runs as a single thread, while the host OS is heavily multi-threaded
• In an iOS app, code execution is triggered by user or external events

We can not control in which thread our Lua methods are called!
• The iOS bridge has to make Lua work in a multi-threaded environment
• Our solution:

• Every top-level Lua code invocation runs in its own Lua thread (i.e.
lua_State)

• A simple scheduler allows to execute only one Lua thread at a given
time, with well-defined deschedule points
• Looks simple but works great in practice!
Design Patterns Translation
Making native design patterns
feel natural in Lua
About Native Design Patterns
• An API is not just about types and function: how to use it is even more
important.

• Typical design patterns define the expected way to use the APIs.

• The iOS / macOS SDKs rely on strong design patterns and
conventions: MVC, delegation, observing, target-action…

• Making these design patterns feel natural in Lua is key for the bridge
usability!
Now, a few examples of design patterns adaptation to Lua:
Pattern 1: Subclass to Customize
This is how Controllers work in iOS.

We need the possibility to subclass native classes in Lua!
local ViewController = class.createClass ("ViewController", objc.UIViewController)
function ViewController:loadView ()
-- Create a view programmatically.
self.view = objc.UIView:new()
end
function ViewController:viewDidLoad ()
self[ViewController.superclass]:viewDidLoad()
self:configureView ()
self:addMessageHandler (ViewController, "refreshView")
end
function ViewController:configureView ()
-- Put here the code configuring the controller's view
self.view.backgroundColor = objc.UIColor.whiteColor
end
function ViewController:refreshView()
-- Update the controller's view
self:configureView()
-- Other refresh actions
-- ...
end
return ViewController
Two native methods
overriden in Lua
Two Lua methods
not visible from the
native code
This creates a Lua subclass
of native UIViewController
Pattern 2: delegation
• A delegate object is used to customize or control the actions of a SDK object, by
implementing a well-defined API contract declared as a protocol. A delegate object can
be of any class, provided it implements the expected protocol.

• A Lua object can be declared as the delegate of a native object.

• Publishing a protocol makes the protocol’s methods defined by a Lua class callable from
the native code
local TableDataSource = class.createClass("TableDataSource")
function TableDataSource:setTableView (tableView)
self.tableView = tableView
tableView.datasource = self
end
TableDataSource:publishObjcProtocols "UITableViewDataSource"
function TableDataSource:tableView_numberOfRowsInSection (tableView, section)
local objects = self.objects
return objects and #objects or 0
end
function TableDataSource:tableView_cellForRowAtIndexPath (tableView, indexPath)
local cell = tableView:dequeueReusableCellWithIdentifier_forIndexPath("Cell", indexPath)
local object = self.objects [indexPath.row + 1]
cell.textLabel.text = object.description
return cell
end
This creates a Lua class
(with no native superclass)
Implement mandatory methods of
protocol UITableViewDataSource
Instances of this class are
used as ‘data source of a
native UITableView object
Pattern 3: closure parameters
• Closure (aka ObjC blocks) parameters are used for synchronous or
asynchronous callback in many places of the iOS / macOS SDKs

• Lua functions are a perfect match for closure parameters!
function CollectionController:setCollectionText(text)
local words = {}
local wordsCount = 0
text:enumerateSubstringsInRange_options_usingBlock
(NSRange(0, text.length),
NsString.Enumeration.ByWords,
function(word, range, effectiveRange)
wordsCount = wordsCount + 1
words[wordsCount] = word
end)
self.textWords = words
self.collectionView:reloadData()
end
This native NSString
method takes a
closure parameter.
You simply pass a
Lua function for this
closure parameter
Bindings
Generation
Supporting large OS SDKs
thanks to automation
SDK Bindings Generation
• Two main components in the bridge

• Generic bridge library: memory & threads management, OO framework, generic type conversion and
function call bridging

• Bindings: the specific code that makes the bridge work for a given SDK or
API
• iOS / macOS SDKs are quite big (~1900 header files for iOS, 2300 for macOS)

Bindings generation has to be automated
• Use clang (llvm) for parsing C / Objective-C headers
• Bindings generation is based on the AST generated by clang
C / ObjC
header
file
clang
Abstract
syntax
tree
bindings
gen.
Bindings Libraries
Bindings Metadata
Bindings Lua Interface
SDK Bindings Generation
C / ObjC
header
file
clang
Abstract
syntax
tree
bindings
gen.
Bindings Libraries
Bindings Metadata
Bindings Lua Interface
• Bindings Libraries

• Mix of generated code and declarative typing information

• Linked with the target application

• Include: constants, enums, structs, C functions, classes with methods and
properties, protocols …

• Loaded as Lua modules

• Bindings Metadata

• Used by the IDE
• Bindings Lua Interface

• A user-readable Lua version of the SDK
local UiGestureRecognizer = require "UIKit.UIGestureRecognizer"
IDE Integration
Supporting native SDKs
in the IDE for a better
coding experience
Bridge - IDE Integration
• Goal: help the developer to use the native SDK(s) in Lua
• In the Lua source code editor

• auto-completion of SDK symbols
defined in Bindings Libraries
Bridge - IDE Integration
• Goal: help the developer to use the native SDK(s) in Lua
• In the Lua source code editor

• auto-completion of SDK symbols
defined in Bindings Libraries
• For build configuration of target app

• by computing bindings-related
dependencies in Lua modules
• In the Lua debugger

• inspect native types in the
Variables Inspector

• interrupt on error in case of failed
type conversion or wrong
nullability … and continue
execution after fixing the issue!
Bridge - IDE Integration
• Goal: help the developer to use the native SDK(s) in Lua
• In the Lua source code editor

• auto-completion of SDK symbols
defined in Bindings Libraries
• For build configuration of target app

• by computing bindings-related
dependencies in Lua modules
• In the Lua debugger

• inspect native types in the
Variables Inspector

• interrupt on error in case of failed
type conversion or wrong
nullability … and continue
execution after fixing the issue!
Tour completed
What have we seen?
Recap
Needed for this bridge:
• A well-defined goal for the iOS bridge.
• Solid low-level foundations: types, memory and threads.
• Careful transposition of the SDK’s main design patterns.
• Bindings generation tools to support large SDKs.
• IDE integration to brings additional value to the user.
For More Information
• About CodeFlow and live-coding on iOS

• Explore https://www.celedev.com

• Play with live-coding iOS with Lua: https://www.celedev.com/en/download/

• Follow the project: @celedev

• About the iOS bridge

• Read our Get Started with Lua series 

https://www.celedev.com/en/documentation/get-started/get-started-with-lua

• Part 2: CodeFlow object framework

• Part 3: CodeFlow native bridge
Thank You!
Questions?
Jean-Luc Jumpertz
@JLJump
www.celedev.com
@celedev

Contenu connexe

Tendances

Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeSean P. Floyd
 
Counterclockwise past present future
Counterclockwise  past present futureCounterclockwise  past present future
Counterclockwise past present futurelolopetit
 
Introduction and hacking OpenStack, Pycon India
Introduction and hacking OpenStack,  Pycon IndiaIntroduction and hacking OpenStack,  Pycon India
Introduction and hacking OpenStack, Pycon IndiaAtul Jha
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersDiego Freniche Brito
 
Scala and its Ecosystem
Scala and its EcosystemScala and its Ecosystem
Scala and its EcosystemPetr Hošek
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using ScalaNgoc Dao
 
Building next gen android library with gradle
Building next gen android library with gradleBuilding next gen android library with gradle
Building next gen android library with gradleAnton Rutkevich
 
Core Java
Core JavaCore Java
Core JavaNA
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
javerosmx-2015-marzo-groovy-java8-comparison
javerosmx-2015-marzo-groovy-java8-comparisonjaverosmx-2015-marzo-groovy-java8-comparison
javerosmx-2015-marzo-groovy-java8-comparisonDomingo Suarez Torres
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript EngineGary Yeh
 
Scala on-android
Scala on-androidScala on-android
Scala on-androidlifecoder
 

Tendances (19)

Hacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or RuntimeHacking Java - Enhancing Java Code at Build or Runtime
Hacking Java - Enhancing Java Code at Build or Runtime
 
Counterclockwise past present future
Counterclockwise  past present futureCounterclockwise  past present future
Counterclockwise past present future
 
Introduction and hacking OpenStack, Pycon India
Introduction and hacking OpenStack,  Pycon IndiaIntroduction and hacking OpenStack,  Pycon India
Introduction and hacking OpenStack, Pycon India
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
Scala and its Ecosystem
Scala and its EcosystemScala and its Ecosystem
Scala and its Ecosystem
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
History of java
History of javaHistory of java
History of java
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
 
Building next gen android library with gradle
Building next gen android library with gradleBuilding next gen android library with gradle
Building next gen android library with gradle
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Basic java tutorial
Basic java tutorialBasic java tutorial
Basic java tutorial
 
Core Java
Core JavaCore Java
Core Java
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
javerosmx-2015-marzo-groovy-java8-comparison
javerosmx-2015-marzo-groovy-java8-comparisonjaverosmx-2015-marzo-groovy-java8-comparison
javerosmx-2015-marzo-groovy-java8-comparison
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript Engine
 
Scala on-android
Scala on-androidScala on-android
Scala on-android
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
 

Similaire à Programming iOS in Lua - A bridge story

Containers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellContainers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellEugene Fedorenko
 
Manage your external libraries with CocoaPods
Manage your external libraries with CocoaPodsManage your external libraries with CocoaPods
Manage your external libraries with CocoaPodsJuan C Catalan
 
Node Architecture.pptx
Node Architecture.pptxNode Architecture.pptx
Node Architecture.pptxAhmed Hassan
 
Understanding iOS from an Android perspective
Understanding iOS from an Android perspectiveUnderstanding iOS from an Android perspective
Understanding iOS from an Android perspectiveLauren Yew
 
RubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on RailsRubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on Railselliando dias
 
Containerize all the things!
Containerize all the things!Containerize all the things!
Containerize all the things!Mike Melusky
 
Rails Applications with Docker
Rails Applications with DockerRails Applications with Docker
Rails Applications with DockerLaura Frank Tacho
 
CoconutKit
CoconutKitCoconutKit
CoconutKitdefagos
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Andrey Breslav
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
AppScale @ LA.rb
AppScale @ LA.rbAppScale @ LA.rb
AppScale @ LA.rbChris Bunch
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Nilesh Panchal
 
Mobile Fest 2018. Алексей Лизенко. Make your project great again
Mobile Fest 2018. Алексей Лизенко. Make your project great againMobile Fest 2018. Алексей Лизенко. Make your project great again
Mobile Fest 2018. Алексей Лизенко. Make your project great againMobileFest2018
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
MJ Berends talk from AWS Chicago Summit
MJ Berends talk from AWS Chicago SummitMJ Berends talk from AWS Chicago Summit
MJ Berends talk from AWS Chicago SummitAWS Chicago
 

Similaire à Programming iOS in Lua - A bridge story (20)

ruby-cocoa
ruby-cocoaruby-cocoa
ruby-cocoa
 
ruby-cocoa
ruby-cocoaruby-cocoa
ruby-cocoa
 
Containers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellContainers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshell
 
Manage your external libraries with CocoaPods
Manage your external libraries with CocoaPodsManage your external libraries with CocoaPods
Manage your external libraries with CocoaPods
 
Node Architecture.pptx
Node Architecture.pptxNode Architecture.pptx
Node Architecture.pptx
 
Understanding iOS from an Android perspective
Understanding iOS from an Android perspectiveUnderstanding iOS from an Android perspective
Understanding iOS from an Android perspective
 
RubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on RailsRubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on Rails
 
Containerize all the things!
Containerize all the things!Containerize all the things!
Containerize all the things!
 
Rails Applications with Docker
Rails Applications with DockerRails Applications with Docker
Rails Applications with Docker
 
CoconutKit
CoconutKitCoconutKit
CoconutKit
 
Node js internal
Node js internalNode js internal
Node js internal
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
AppScale @ LA.rb
AppScale @ LA.rbAppScale @ LA.rb
AppScale @ LA.rb
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
 
Mobile Fest 2018. Алексей Лизенко. Make your project great again
Mobile Fest 2018. Алексей Лизенко. Make your project great againMobile Fest 2018. Алексей Лизенко. Make your project great again
Mobile Fest 2018. Алексей Лизенко. Make your project great again
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Core JavaScript
Core JavaScriptCore JavaScript
Core JavaScript
 
MJ Berends talk from AWS Chicago Summit
MJ Berends talk from AWS Chicago SummitMJ Berends talk from AWS Chicago Summit
MJ Berends talk from AWS Chicago Summit
 

Dernier

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 

Dernier (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 

Programming iOS in Lua - A bridge story

  • 1. A bridge story Programming iOS in Lua Lua Workshop 2016 Jean-Luc Jumpertz @JLJump October 14, 2016
  • 2. CodeFlow Live Application Development Environment for iOS, tvOS & macOS
  • 3. CodeFlow Live Application Development Environment for iOS, tvOS & macOS instant feedback on real devices native OS SDK live code live assets true debugger Lua language live storyboards native project APIs
  • 4. A Bridge? What for? Transparent development of iOS code in Lua
  • 5. Goals of the iOS bridge • Enable the development of iOS apps in Lua using the native OS SDK • Make the use of the native SDK feel natural in Lua • Make it easy for a Swift or ObjC developer to move to Lua Transparent integration between Lua and iOS • Not the same objective as some other bridges • Exposing Lua-specific features to the iOS native world was not in the scope, nor was the definition of a Swift / ObjC version of the Lua C API. • Low-level aspects of the native world had to be hidden from the Lua code
  • 6. The foundations Dealing with type conversions, memory management, and threads
  • 7. Mixing Lua and native types • Different typing systems • Lua: typed values; untyped function parameters • C world: typed variables and parameters; ABI • Calling native from Lua: convert parameters to the expected types • Easy for base types, more complex for structured types, objects, collections… • Doing this conversion is the first role of a bridge • Example: expose a struct to Lua • Pseudo-object with constructor, accessors, … and methods • Automatic Lua table → struct conversion in function calls struct CGPoint { CGFloat x; CGFloat y; }; local CGPoint = struct.CGPoint:_structInterface { x = 0.0, y = 0.0 } local aPoint = struct.CGPoint (100, 50) aPoint.x = 200 self.view.center = aPoint -- ... self.view.center = { x = 150, y = aPoint.y + 20 } LuaC
  • 8. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting
  • 9. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting Object B +1 Object B +2 Object B +1 Object B +0 Object A Create Object C Retain Object A Release Object C Release
  • 10. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting • Managing objects lifecycle • A native object passed to the Lua runtime is retained until GC-ed, and released by its finalizer metamethod • A Lua value passed to the native world maintains a Lua reference to prevent GC (luaL_ref) and remove this reference when not used anymore. (luaL_unref)
  • 11. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting • Managing objects lifecycle • A native object passed to the Lua runtime is retained until GC-ed, and released by its finalizer metamethod • A Lua value passed to the native world maintains a Lua reference to prevent GC (luaL_ref) and remove this reference when not used anymore. (luaL_unref) • The retain cycle problem • It is possible from Lua, to create a retain cycle between native objects
  • 12. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting • Managing objects lifecycle • A native object passed to the Lua runtime is retained until GC-ed, and released by its finalizer metamethod • A Lua value passed to the native world maintains a Lua reference to prevent GC (luaL_ref) and remove this reference when not used anymore. (luaL_unref) • The retain cycle problem • It is possible from Lua, to create a retain cycle between native objects Object A +1 Object B +1
  • 13. Making Memory Models Coexist • Different memory models • Lua: garbage collector • ObjC runtime: automatic reference counting • Managing objects lifecycle • A native object passed to the Lua runtime is retained until GC-ed, and released by its finalizer metamethod • A Lua value passed to the native world maintains a Lua reference to prevent GC (luaL_ref) and remove this reference when not used anymore. (luaL_unref) • The retain cycle problem • It is possible from Lua, to create a retain cycle between native objects memory leak! • Weak object references are the solution • Object reference getters: weakRef and strongRef
 • A weak reference become an all-nil object when the referenced object is deallocated local weakSelf = self.weakRef
  • 14. Running Lua in a Threaded World • Lua runs as a single thread, while the host OS is heavily multi-threaded • In an iOS app, code execution is triggered by user or external events We can not control in which thread our Lua methods are called! • The iOS bridge has to make Lua work in a multi-threaded environment
  • 15. Running Lua in a Threaded World • Lua runs as a single thread, while the host OS is heavily multi-threaded • In an iOS app, code execution is triggered by user or external events We can not control in which thread our Lua methods are called! • The iOS bridge has to make Lua work in a multi-threaded environment • Our solution: • Every top-level Lua code invocation runs in its own Lua thread (i.e. lua_State) • A simple scheduler allows to execute only one Lua thread at a given time, with well-defined deschedule points • Looks simple but works great in practice!
  • 16. Design Patterns Translation Making native design patterns feel natural in Lua
  • 17. About Native Design Patterns • An API is not just about types and function: how to use it is even more important. • Typical design patterns define the expected way to use the APIs. • The iOS / macOS SDKs rely on strong design patterns and conventions: MVC, delegation, observing, target-action… • Making these design patterns feel natural in Lua is key for the bridge usability! Now, a few examples of design patterns adaptation to Lua:
  • 18. Pattern 1: Subclass to Customize This is how Controllers work in iOS. We need the possibility to subclass native classes in Lua! local ViewController = class.createClass ("ViewController", objc.UIViewController) function ViewController:loadView () -- Create a view programmatically. self.view = objc.UIView:new() end function ViewController:viewDidLoad () self[ViewController.superclass]:viewDidLoad() self:configureView () self:addMessageHandler (ViewController, "refreshView") end function ViewController:configureView () -- Put here the code configuring the controller's view self.view.backgroundColor = objc.UIColor.whiteColor end function ViewController:refreshView() -- Update the controller's view self:configureView() -- Other refresh actions -- ... end return ViewController Two native methods overriden in Lua Two Lua methods not visible from the native code This creates a Lua subclass of native UIViewController
  • 19. Pattern 2: delegation • A delegate object is used to customize or control the actions of a SDK object, by implementing a well-defined API contract declared as a protocol. A delegate object can be of any class, provided it implements the expected protocol. • A Lua object can be declared as the delegate of a native object. • Publishing a protocol makes the protocol’s methods defined by a Lua class callable from the native code local TableDataSource = class.createClass("TableDataSource") function TableDataSource:setTableView (tableView) self.tableView = tableView tableView.datasource = self end TableDataSource:publishObjcProtocols "UITableViewDataSource" function TableDataSource:tableView_numberOfRowsInSection (tableView, section) local objects = self.objects return objects and #objects or 0 end function TableDataSource:tableView_cellForRowAtIndexPath (tableView, indexPath) local cell = tableView:dequeueReusableCellWithIdentifier_forIndexPath("Cell", indexPath) local object = self.objects [indexPath.row + 1] cell.textLabel.text = object.description return cell end This creates a Lua class (with no native superclass) Implement mandatory methods of protocol UITableViewDataSource Instances of this class are used as ‘data source of a native UITableView object
  • 20. Pattern 3: closure parameters • Closure (aka ObjC blocks) parameters are used for synchronous or asynchronous callback in many places of the iOS / macOS SDKs • Lua functions are a perfect match for closure parameters! function CollectionController:setCollectionText(text) local words = {} local wordsCount = 0 text:enumerateSubstringsInRange_options_usingBlock (NSRange(0, text.length), NsString.Enumeration.ByWords, function(word, range, effectiveRange) wordsCount = wordsCount + 1 words[wordsCount] = word end) self.textWords = words self.collectionView:reloadData() end This native NSString method takes a closure parameter. You simply pass a Lua function for this closure parameter
  • 21. Bindings Generation Supporting large OS SDKs thanks to automation
  • 22. SDK Bindings Generation • Two main components in the bridge • Generic bridge library: memory & threads management, OO framework, generic type conversion and function call bridging • Bindings: the specific code that makes the bridge work for a given SDK or API • iOS / macOS SDKs are quite big (~1900 header files for iOS, 2300 for macOS) Bindings generation has to be automated • Use clang (llvm) for parsing C / Objective-C headers • Bindings generation is based on the AST generated by clang C / ObjC header file clang Abstract syntax tree bindings gen. Bindings Libraries Bindings Metadata Bindings Lua Interface
  • 23. SDK Bindings Generation C / ObjC header file clang Abstract syntax tree bindings gen. Bindings Libraries Bindings Metadata Bindings Lua Interface • Bindings Libraries • Mix of generated code and declarative typing information • Linked with the target application • Include: constants, enums, structs, C functions, classes with methods and properties, protocols … • Loaded as Lua modules
 • Bindings Metadata • Used by the IDE • Bindings Lua Interface • A user-readable Lua version of the SDK local UiGestureRecognizer = require "UIKit.UIGestureRecognizer"
  • 24. IDE Integration Supporting native SDKs in the IDE for a better coding experience
  • 25. Bridge - IDE Integration • Goal: help the developer to use the native SDK(s) in Lua • In the Lua source code editor • auto-completion of SDK symbols defined in Bindings Libraries
  • 26. Bridge - IDE Integration • Goal: help the developer to use the native SDK(s) in Lua • In the Lua source code editor • auto-completion of SDK symbols defined in Bindings Libraries • For build configuration of target app • by computing bindings-related dependencies in Lua modules • In the Lua debugger • inspect native types in the Variables Inspector • interrupt on error in case of failed type conversion or wrong nullability … and continue execution after fixing the issue!
  • 27. Bridge - IDE Integration • Goal: help the developer to use the native SDK(s) in Lua • In the Lua source code editor • auto-completion of SDK symbols defined in Bindings Libraries • For build configuration of target app • by computing bindings-related dependencies in Lua modules • In the Lua debugger • inspect native types in the Variables Inspector • interrupt on error in case of failed type conversion or wrong nullability … and continue execution after fixing the issue!
  • 29. Recap Needed for this bridge: • A well-defined goal for the iOS bridge. • Solid low-level foundations: types, memory and threads. • Careful transposition of the SDK’s main design patterns. • Bindings generation tools to support large SDKs. • IDE integration to brings additional value to the user.
  • 30. For More Information • About CodeFlow and live-coding on iOS • Explore https://www.celedev.com • Play with live-coding iOS with Lua: https://www.celedev.com/en/download/ • Follow the project: @celedev • About the iOS bridge • Read our Get Started with Lua series 
 https://www.celedev.com/en/documentation/get-started/get-started-with-lua • Part 2: CodeFlow object framework • Part 3: CodeFlow native bridge