Lua is a lightweight scripting language that is easily embeddable. It incorporates many innovations from other languages like Python and Ruby. The document discusses Lua's core concepts including data types, tables, functions, environments, object orientation, and the C API. It provides code examples to demonstrate Lua's features like iterators, coroutines, metatables, and using Lua to configure applications by loading rules from a file.
This document provides an overview of Lua tables and their use as different data structures. It discusses how Lua tables can be used as arrays, hash tables, matrices, linked lists, stacks, queues, sets and more. It covers common table operations like creation, accessing and modifying elements, iterating over elements, and more. The document aims to explain how to adapt Lua tables to represent multiple data structures.
Get started with Lua - Hackference 2016Etiene Dalcol
Lua is a very fast, elegant and powerful dynamic language. It’s an excellent tool for robust applications or slim embedded systems. It found a niche in game development with big names such as “Grim Fandango”, “World of Warcraft” and “Angry Birds”. This talk will present what makes Lua different from other interpreted languages, the evolution of the Lua ecosystem, some key concepts of the language, and show you why Lua is the next language to add to your skill set.
The document discusses various Python interpreters:
- CPython is the default interpreter but has a Global Interpreter Lock (GIL) limiting performance on multi-core systems.
- Jython and IronPython run Python on the JVM and CLR respectively, allowing true concurrency but can be slower than CPython.
- PyPy uses a just-in-time (JIT) compiler which can provide huge performance gains compared to CPython as shown on speed.pypy.org.
- Unladen Swallow aimed to add JIT compilation to CPython but was merged into Python 3.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
GUL UC3M - Introduction to functional programmingDavid Muñoz Díaz
Functional programming models computations as expressions rather than instructions. It emphasizes immutable data and functions, and avoids mutable state. Some key aspects of functional programming include: treating functions as first-class values, recursion instead of loops, lazy evaluation, and immutable data structures. While any language can support aspects of functional programming, some languages are better optimized for the functional style.
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
This document provides an overview of Lua tables and their use as different data structures. It discusses how Lua tables can be used as arrays, hash tables, matrices, linked lists, stacks, queues, sets and more. It covers common table operations like creation, accessing and modifying elements, iterating over elements, and more. The document aims to explain how to adapt Lua tables to represent multiple data structures.
Get started with Lua - Hackference 2016Etiene Dalcol
Lua is a very fast, elegant and powerful dynamic language. It’s an excellent tool for robust applications or slim embedded systems. It found a niche in game development with big names such as “Grim Fandango”, “World of Warcraft” and “Angry Birds”. This talk will present what makes Lua different from other interpreted languages, the evolution of the Lua ecosystem, some key concepts of the language, and show you why Lua is the next language to add to your skill set.
The document discusses various Python interpreters:
- CPython is the default interpreter but has a Global Interpreter Lock (GIL) limiting performance on multi-core systems.
- Jython and IronPython run Python on the JVM and CLR respectively, allowing true concurrency but can be slower than CPython.
- PyPy uses a just-in-time (JIT) compiler which can provide huge performance gains compared to CPython as shown on speed.pypy.org.
- Unladen Swallow aimed to add JIT compilation to CPython but was merged into Python 3.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
GUL UC3M - Introduction to functional programmingDavid Muñoz Díaz
Functional programming models computations as expressions rather than instructions. It emphasizes immutable data and functions, and avoids mutable state. Some key aspects of functional programming include: treating functions as first-class values, recursion instead of loops, lazy evaluation, and immutable data structures. While any language can support aspects of functional programming, some languages are better optimized for the functional style.
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
This document discusses various techniques for optimizing Python code, including:
1. Using the right algorithms and data structures to minimize time complexity, such as choosing lists, sets or dictionaries based on needed functionality.
2. Leveraging Python-specific optimizations like string concatenation, lookups, loops and imports.
3. Profiling code with tools like timeit, cProfile and visualizers to identify bottlenecks before optimizing.
4. Optimizing only after validating a performance need and starting with general strategies before rewriting hotspots in Python or other languages. Premature optimization can complicate code.
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
Functional programming is finally a first class citizen in the Cocoa toolset! But, as you may have heard, Swift is not necessarily a pure functional language. And in embracing the functional paradigm, do you need to throw out your knowledge and experience with Object Oriented programming? Saul Mora shows that it turns out you can have your cake and eat it too!
Euro python2011 High Performance PythonIan Ozsvald
I ran this as a 4 hour tutorial at EuroPython 2011 to teach High Performance Python coding.
Techniques covered include bottleneck analysis by profiling, bytecode analysis, converting to C using Cython and ShedSkin, use of the numerical numpy library and numexpr, multi-core and multi-machine parallelisation and using CUDA GPUs.
Write-up with 49 page PDF report: http://ianozsvald.com/2011/06/29/high-performance-python-tutorial-v0-1-from-my-4-hour-tutorial-at-europython-2011/
This document provides an introduction to Python programming including installation, basic syntax, data types, control flow, modules, sockets, structs, pwntools, vulnerabilities, practice problems, and references for further learning. It covers topics such as printing, taking input, lists, arithmetic, conditional statements, loops, functions, importing modules, sending/receiving data over sockets, packing/unpacking integers, using pwntools, and exploiting vulnerabilities like pickle injection. Example code is provided throughout to demonstrate the concepts.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
This document provides an introduction to Scala. It discusses:
- Who the author is and their background with Scala and Spark
- Why Scala is a scalable language that runs on the JVM and supports object oriented and functional programming
- How to install Scala and use the Scala interpreter
- Basic Scala syntax like defining values and variables, type inference, strings, tuples, objects, importing classes
- Common functions and operations like map, reduce, anonymous functions, pattern matching
- Code samples for RDD relations and SparkPi
- Tips for using Scala in practice including SBT and good IDEs like IntelliJ
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
This document discusses refactoring Java code to Clojure using macros. It provides examples of refactoring Java code that uses method chaining to equivalent Clojure code using the threading macros (->> and -<>). It also discusses other Clojure features like type hints, the doto macro, and polyglot projects using Leiningen.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
This document discusses ways to introduce functional programming concepts into Java code using existing Java 8 features, third-party libraries like Guava and LambdaJ, and by implementing common functional patterns and data structures yourself. It provides examples of using higher order functions, pure functions, recursion, and currying in Java code. It also summarizes capabilities of the Guava and LambdaJ libraries for functional programming in Java.
This document discusses various topics related to Java class design including:
- The first object oriented programming language was Simula from 1965
- Examples are provided to demonstrate polymorphism and abstract classes in Java
- The java.time package provides improved date/time functionality over java.util.Date
- Design principles like single responsibility, open/closed, Liskov substitution, and others are covered
- Tools for exploring class design structures like dependencies are listed
- Local meetups focused on software design and development are shared.
This document provides an overview and agenda for a presentation on Full Stack Clojure. It introduces Clojure and why it was designed, discusses some of its core principles like immutability and functional programming, and provides examples of basic Clojure concepts like data literals, syntax, and persistent data structures. The presentation aims to explain Clojure and demonstrate how to build full stack applications with it.
The document discusses programming with futures in Java and Scala. It introduces futures in Java 8 using CompletableFuture and shows how they allow composing asynchronous operations without blocking threads. It then discusses how streams and futures in Java 8 share similar composition concepts using thenApply and thenCompose. The talk moves on to introduce more abstract concepts from category theory - monads, foldables and monoids. It shows how these concepts can be implemented for futures and lists to provide generic sequencing and folding of asynchronous and synchronous operations in a precise way.
In this talk I presented three important topics in Kotlin Standard Library: Scope Functions (let, apply, also, run and with); Annotations (Deprecated, Experimental, Jvm*, DslMarker); and Delegates (lazy, vetoable, observable)
Emerging Languages: A Tour of the HorizonAlex Payne
A tour of a number of new programming languages, organized by the job they're best suited for. Presented at Philadelphia Emerging Technology for the Enterprise 2012.
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
Lua is a scripting language that can be embedded in large systems. The author initially found Lua irritating due to its verbose syntax and lack of operators like +=. However, Lua proved useful for applications like a web application firewall and camera scripting. Lua's performance, small size, extensibility and tables make it well-suited for these domains. Lua's metatables provide powerful abilities like sandboxing code, lazy loading, and object orientation. Overall Lua is a great embedded language once its initial syntax irritations are overcome.
This document provides an introduction to JavaScript web development. It covers key concepts like AJAX architecture, unobtrusive JavaScript, CSS, and how they interact. JavaScript allows dynamic interaction and filtering of HTML content. The document demonstrates JavaScript features like variables, arrays, objects, JSON, loops, functions, and more. It also discusses advantages of CSS for layout and separation of concerns from HTML.
1) The document discusses various issues and developments related to the evolution of web standards including ECMAScript, WebAssembly, and CSS.
2) It outlines goals and features of WebAssembly including being portable, efficient, safe, open, and integrated with the web. The MVP will have functionality similar to asm.js with future additions.
3) The author is available for contact and provides links to documentation on topics discussed in the slides like WebAssembly, PostCSS, and Houdini.
Web development with Lua and Sailor @ GeeCon 2015Etiene Dalcol
Lua is a very fast and powerful scripting language that can be easily embeddable. It can be used to develop robust applications and has been shining in industries like game development, for example. Lua is also an excellent tool as a general purpose language. However, it's use in web development, despite its great potential and incredible benchmarks, needs to be more widespread. Having had experience as a web programmer, and aiming to learn more about this language, I started a marathon that produced Sailor 0.1, a web MVC framework completely written in Lua after only ten days. Once the quest was completed, the feedback was so interesting that I continued the development. Sailor keeps growing each day, also with the help of contributors. This talk presents the beginnings of Sailor framework, a comparison with other existing tools in Lua, the current stage of Sailor's development today, the official announcement of version 0.3 (Jupiter). This presentation also intends to start a debate on what we can do to spread the idea of using more Lua in web development.
This document discusses various techniques for optimizing Python code, including:
1. Using the right algorithms and data structures to minimize time complexity, such as choosing lists, sets or dictionaries based on needed functionality.
2. Leveraging Python-specific optimizations like string concatenation, lookups, loops and imports.
3. Profiling code with tools like timeit, cProfile and visualizers to identify bottlenecks before optimizing.
4. Optimizing only after validating a performance need and starting with general strategies before rewriting hotspots in Python or other languages. Premature optimization can complicate code.
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
Functional programming is finally a first class citizen in the Cocoa toolset! But, as you may have heard, Swift is not necessarily a pure functional language. And in embracing the functional paradigm, do you need to throw out your knowledge and experience with Object Oriented programming? Saul Mora shows that it turns out you can have your cake and eat it too!
Euro python2011 High Performance PythonIan Ozsvald
I ran this as a 4 hour tutorial at EuroPython 2011 to teach High Performance Python coding.
Techniques covered include bottleneck analysis by profiling, bytecode analysis, converting to C using Cython and ShedSkin, use of the numerical numpy library and numexpr, multi-core and multi-machine parallelisation and using CUDA GPUs.
Write-up with 49 page PDF report: http://ianozsvald.com/2011/06/29/high-performance-python-tutorial-v0-1-from-my-4-hour-tutorial-at-europython-2011/
This document provides an introduction to Python programming including installation, basic syntax, data types, control flow, modules, sockets, structs, pwntools, vulnerabilities, practice problems, and references for further learning. It covers topics such as printing, taking input, lists, arithmetic, conditional statements, loops, functions, importing modules, sending/receiving data over sockets, packing/unpacking integers, using pwntools, and exploiting vulnerabilities like pickle injection. Example code is provided throughout to demonstrate the concepts.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
This document provides an introduction to Scala. It discusses:
- Who the author is and their background with Scala and Spark
- Why Scala is a scalable language that runs on the JVM and supports object oriented and functional programming
- How to install Scala and use the Scala interpreter
- Basic Scala syntax like defining values and variables, type inference, strings, tuples, objects, importing classes
- Common functions and operations like map, reduce, anonymous functions, pattern matching
- Code samples for RDD relations and SparkPi
- Tips for using Scala in practice including SBT and good IDEs like IntelliJ
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
This document discusses refactoring Java code to Clojure using macros. It provides examples of refactoring Java code that uses method chaining to equivalent Clojure code using the threading macros (->> and -<>). It also discusses other Clojure features like type hints, the doto macro, and polyglot projects using Leiningen.
Presented by Stephen Murtagh, Etsy.com, Inc.
TF-IDF (term frequency, inverse document frequency) is a standard method of weighting query terms for scoring documents, and is the method that is used by default in Solr/Lucene. Unfortunately, TF-IDF is really only a measure of rarity, not quality or usefulness. This means it would give more weight to a useless, rare term, such as a misspelling, than to a more useful, but more common, term.
In this presentation, we will discuss our experiences replacing Lucene's TF-IDF based scoring function with a more useful one using information gain, a standard machine-learning measure that combines frequency and specificity. Information gain is much more expensive to compute, however, so this requires periodically computing the term weights outside of Solr/Lucene and making the results accessible within Solr/Lucene.
This document discusses ways to introduce functional programming concepts into Java code using existing Java 8 features, third-party libraries like Guava and LambdaJ, and by implementing common functional patterns and data structures yourself. It provides examples of using higher order functions, pure functions, recursion, and currying in Java code. It also summarizes capabilities of the Guava and LambdaJ libraries for functional programming in Java.
This document discusses various topics related to Java class design including:
- The first object oriented programming language was Simula from 1965
- Examples are provided to demonstrate polymorphism and abstract classes in Java
- The java.time package provides improved date/time functionality over java.util.Date
- Design principles like single responsibility, open/closed, Liskov substitution, and others are covered
- Tools for exploring class design structures like dependencies are listed
- Local meetups focused on software design and development are shared.
This document provides an overview and agenda for a presentation on Full Stack Clojure. It introduces Clojure and why it was designed, discusses some of its core principles like immutability and functional programming, and provides examples of basic Clojure concepts like data literals, syntax, and persistent data structures. The presentation aims to explain Clojure and demonstrate how to build full stack applications with it.
The document discusses programming with futures in Java and Scala. It introduces futures in Java 8 using CompletableFuture and shows how they allow composing asynchronous operations without blocking threads. It then discusses how streams and futures in Java 8 share similar composition concepts using thenApply and thenCompose. The talk moves on to introduce more abstract concepts from category theory - monads, foldables and monoids. It shows how these concepts can be implemented for futures and lists to provide generic sequencing and folding of asynchronous and synchronous operations in a precise way.
In this talk I presented three important topics in Kotlin Standard Library: Scope Functions (let, apply, also, run and with); Annotations (Deprecated, Experimental, Jvm*, DslMarker); and Delegates (lazy, vetoable, observable)
Emerging Languages: A Tour of the HorizonAlex Payne
A tour of a number of new programming languages, organized by the job they're best suited for. Presented at Philadelphia Emerging Technology for the Enterprise 2012.
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
Lua is a scripting language that can be embedded in large systems. The author initially found Lua irritating due to its verbose syntax and lack of operators like +=. However, Lua proved useful for applications like a web application firewall and camera scripting. Lua's performance, small size, extensibility and tables make it well-suited for these domains. Lua's metatables provide powerful abilities like sandboxing code, lazy loading, and object orientation. Overall Lua is a great embedded language once its initial syntax irritations are overcome.
This document provides an introduction to JavaScript web development. It covers key concepts like AJAX architecture, unobtrusive JavaScript, CSS, and how they interact. JavaScript allows dynamic interaction and filtering of HTML content. The document demonstrates JavaScript features like variables, arrays, objects, JSON, loops, functions, and more. It also discusses advantages of CSS for layout and separation of concerns from HTML.
1) The document discusses various issues and developments related to the evolution of web standards including ECMAScript, WebAssembly, and CSS.
2) It outlines goals and features of WebAssembly including being portable, efficient, safe, open, and integrated with the web. The MVP will have functionality similar to asm.js with future additions.
3) The author is available for contact and provides links to documentation on topics discussed in the slides like WebAssembly, PostCSS, and Houdini.
Web development with Lua and Sailor @ GeeCon 2015Etiene Dalcol
Lua is a very fast and powerful scripting language that can be easily embeddable. It can be used to develop robust applications and has been shining in industries like game development, for example. Lua is also an excellent tool as a general purpose language. However, it's use in web development, despite its great potential and incredible benchmarks, needs to be more widespread. Having had experience as a web programmer, and aiming to learn more about this language, I started a marathon that produced Sailor 0.1, a web MVC framework completely written in Lua after only ten days. Once the quest was completed, the feedback was so interesting that I continued the development. Sailor keeps growing each day, also with the help of contributors. This talk presents the beginnings of Sailor framework, a comparison with other existing tools in Lua, the current stage of Sailor's development today, the official announcement of version 0.3 (Jupiter). This presentation also intends to start a debate on what we can do to spread the idea of using more Lua in web development.
Lua is a lightweight scripting language embedded in many applications like Wireshark and Redis. It is small but powerful, with features like closures, coroutines, and metatables. Lua is embedded via its C API and allows for extending applications with modules written in Lua. Popular modules include LuaSocket and LuaSQL. Lua sees widespread use due to its small size, speed, portability, and ability to extend large C/C++ applications with scripting.
Lua as a business logic language in high load applicationIlya Martynov
This report covers our experience building custom HTTP web server used for the delivery of internet advertising. The application design has as one goals finding the right balance between high performance and ease of development. To achieve this goal we are using Lua as a business logic scripting language embedded into C++ application. The report tries to explain how and why we use Lua and how the choice of Lua affects architecture of the application.
What's New in LuaRocks - Lua Workshop 2014 - Hisham MuhammadHisham Muhammad
Slides from my talk "What's new in LuaRocks"
presented at Lua Workshop 2014 in Moscow, Russia
with a brief presentation of LuaRocks,
how things compare now to last year's talk
and some proposals for new features and future directions.
-- Hisham Muhammad
Lua is a lightweight scripting language that can be embedded into C/C++ applications. It is commonly used for extending applications with scripting capabilities. Some key uses of Lua include game scripting, configuration files, extending applications, and implementing logic or rules engines. Lua provides APIs for interacting with the Lua virtual machine from C/C++ code, including pushing and popping values on the Lua stack, calling Lua functions from C, and calling C functions from Lua scripts.
Roll Your Own API Management Platform with nginx and LuaJon Moore
We recently replaced a proprietary API management solution with an in-house implementation built with nginx and Lua that let us get to a continuous delivery practice in a handful of months. Learn about our development process and the overall architecture that allowed us to write minimal amounts of code, enjoying native code performance while permitting interactive codeing, and how we leveraged other open source tools like Vagrant, Ansible, and OpenStack to build an automation-rich delivery pipeline. We will also take an in-depth look at our capacity management approach that differs from the rate limiting concept prevalent in the API community.
This document provides an overview of key accounting concepts, conventions, principles and the accounting cycle. It discusses the accrual basis, going concern concept, matching principle and other fundamental accounting concepts. It also explains accounting equations, debits and credits, journals, ledgers and how to record basic business transactions.
LuaConf 2016 - Becoming a Lua Powered Super HeroCharles McKeever
This document discusses how app developers are using the Lua programming language and Corona SDK to develop apps for multiple platforms. It provides an overview of Corona Labs, the history and goals of Corona SDK, how Lua can be used across platforms, examples of developers using Corona SDK successfully, and resources for learning Lua and Corona SDK.
This document provides an overview of the Go programming language including:
- A brief history of Go from its origins at Google in 2007 to current widespread usage.
- Key features of Go like functions, structs, interfaces, methods, slices, pointers, go-routines and channels.
- Examples of basic Go code demonstrating functions, structs, methods, interfaces, concurrency with go-routines and channels.
- Discussion of things missing from Go like classes, generics and exceptions.
- Quotes from developers commenting both positively and negatively on Go's simplicity and tradeoffs.
- Links to further resources like the Go tour to learn more.
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
Pythran is a an ahead of time compiler that turns modules written in a large subset of Python into C++ meta-programs that can be compiled into efficient native modules. It targets mainly compute intensive part of the code, hence it comes as no surprise that it focuses on scientific applications that makes extensive use of Numpy. Under the hood, Pythran inter-procedurally analyses the program and performs high level optimizations and parallel code generation. Parallelism can be found implicitly in Python intrinsics or Numpy operations, or explicitly specified by the programmer using OpenMP directives directly in the Python source code. Either way, the input code remains fully compatible with the Python interpreter. While the idea is similar to Parakeet or Numba, the approach differs significantly: the code generation is not performed at runtime but offline. Pythran generates C++11 heavily templated code that makes use of the NT2 meta-programming library and relies on any standard-compliant compiler to generate the binary code. We propose to walk through some examples and benchmarks, exposing the current state of what Pythran provides as well as the limit of the approach.
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
This document provides an agenda and overview for a Python training course. The agenda covers key Python topics like dictionaries, conditional statements, loops, functions, modules, input/output, error handling, object-oriented programming and more. The introduction section explains that Python is an interpreted, interactive and object-oriented language well-suited for beginners. It also outlines features like rapid development, automatic memory management and support for procedural and object-oriented programming. The document concludes by explaining Python's core data types including numbers, strings, lists, tuples and dictionaries.
This document discusses monads in functional programming. It provides examples of optionals, arrays, and functions in Swift that exhibit monadic properties. It then defines monads more formally and describes some common monad types like the writer, reader, and IO monads. It shows how monads allow encapsulating effects like logging or environment variables while preserving referential transparency. The document concludes by discussing potential applications of monads to mobile apps.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
This document provides an overview of functional programming concepts in Ruby. It discusses the history and advantages of functional programming, comparing the functional and object-oriented paradigms. It introduces functional programming concepts like pure functions, recursion, immutable data, and higher-order functions. It demonstrates how these concepts can be applied in Ruby using functions, closures, currying, composition, and the Enumerable module. Overall, the document serves as a high-level introduction to thinking functionally in Ruby.
This document provides a quick tour of the Python programming language. It introduces basic Python concepts like data types, variables, operators, conditional statements, loops, and functions. It explains how to get user input, perform type conversions, and work with common data types like integers, floats, strings, and booleans. It also demonstrates how to define functions, use default arguments and keyword arguments, and handle global variables. The document uses examples to illustrate concepts like arithmetic operations, string slicing, indexing, concatenation, and repetition.
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologiesit-people
The document describes a talk on optimizing Python performance through just-in-time compilation. It discusses how the CPython interpreter works by evaluating bytecode through an evaluation loop. It then talks about how PyPy achieves faster performance through jit compilation of hot loops detected via tracing. The talk dives into the RPython language used to implement PyPy and shows an example of compiling a small Python program to C with RPython. It also discusses using partial evaluation to specialize an interpreter for constant inputs.
This presentation is part of a talk by Martin j. Logan on the essentials of programming in the erlang language. The talk covers:
Data Types
Modules and Functions
State Management
Distribution
Fault Tolerance
The code for this talk can be found at github:
git://github.com/martinjlogan/ErlangBootstrap.git
https://github.com/martinjlogan/ErlangBootstrap
Functions allow programmers to organize and reuse code. There are three types of functions: built-in functions, modules, and user-defined functions. User-defined functions are created using the def keyword and can take parameters and arguments. Functions can return values and have different scopes depending on if a variable is local or global. Recursion is when a function calls itself, and is useful for breaking down complex problems into simpler sub-problems. Common recursive functions calculate factorials, Fibonacci numbers, and generate the Pascal's triangle.
This document provides an overview of basic data structures concepts. It discusses bits and data types, different numeric representations like binary and decimal. It introduces common data types used in programming like integers and floats. It also covers abstract data types and provides examples like stacks, queues and lists. The document describes iterative and recursive algorithms for problems like factorial calculation, binary search and the Towers of Hanoi. It analyzes the time complexity of algorithms like selection sort.
The document discusses functions in mathematics and programming. In mathematics, a function defines a relationship between inputs and outputs. The domain is the set of valid inputs, and the range is the set of valid outputs. In programming, functions perform actions and return values. The argument type specifies valid input types, analogous to the mathematical domain, while the return type specifies the output type, analogous to the range. The C standard library contains common mathematical functions like abs, sqrt, and cos. Functions can be used in expressions and assignments like variables.
The document discusses functions in C programming. It begins by explaining what functions are and why they are useful. Functions help modularize programs, avoid code repetition, and allow for software reusability. Key benefits of using functions include divide and conquer programming and abstraction. The document then provides examples of function definitions, prototypes, parameters, return values, and scope. It also discusses calling functions, libraries, recursion, and other concepts related to functions in C.
The document discusses 5 programming languages that the author has learned over the years: Ruby, Erlang, Haskell, Common Lisp, and Clojure. For each language, it provides a brief overview of its origins, paradigms, and interesting features. It encourages readers to try the languages if they are interested in functional programming, parallelism, strong typing, metaprogramming, or Lisp dialects on the JVM.
Porque aprender haskell me fez um programador python melhor?UFPA
The document discusses how learning Haskell made the author a better Python programmer. It argues that by learning Haskell, the author was able to better understand Python code, code written by others, the Python language itself, and frameworks built for Python. Learning Haskell provided a deeper understanding of programming languages in general and allowed the author to critically evaluate their own language choices.
This document provides an overview of the Python programming language. It includes several code examples and summaries of key Python concepts like strings, lists, tuples, dictionaries, files, regular expressions, and object-oriented programming. It also lists some common Python functions and modules for tasks like HTTP requests and database access. The document aims to introduce Python's main features and provide basic code samples to help new Python learners.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
This document compares and contrasts the programming languages Perl and Haskell. It discusses their differences in terms of being dynamic vs static, imperative vs functional, and weakly vs strongly typed. It provides examples of how similar tasks like mapping, doubling values, and finding lengths can be accomplished in both languages. It also explores some of the challenges that arise from Perl's scalar/list context and Haskell's use of monads and strong static types. Overall, the document examines the different philosophies behind Perl and Haskell while also showing how influences have flowed between the communities over time.
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
From Natural Language to Structured Solr Queries using LLMsSease
This talk draws on experimentation to enable AI applications with Solr. One important use case is to use AI for better accessibility and discoverability of the data: while User eXperience techniques, lexical search improvements, and data harmonization can take organizations to a good level of accessibility, a structural (or “cognitive” gap) remains between the data user needs and the data producer constraints.
That is where AI – and most importantly, Natural Language Processing and Large Language Model techniques – could make a difference. This natural language, conversational engine could facilitate access and usage of the data leveraging the semantics of any data source.
The objective of the presentation is to propose a technical approach and a way forward to achieve this goal.
The key concept is to enable users to express their search queries in natural language, which the LLM then enriches, interprets, and translates into structured queries based on the Solr index’s metadata.
This approach leverages the LLM’s ability to understand the nuances of natural language and the structure of documents within Apache Solr.
The LLM acts as an intermediary agent, offering a transparent experience to users automatically and potentially uncovering relevant documents that conventional search methods might overlook. The presentation will include the results of this experimental work, lessons learned, best practices, and the scope of future work that should improve the approach and make it production-ready.
AI in the Workplace Reskilling, Upskilling, and Future Work.pptxSunil Jagani
Discover how AI is transforming the workplace and learn strategies for reskilling and upskilling employees to stay ahead. This comprehensive guide covers the impact of AI on jobs, essential skills for the future, and successful case studies from industry leaders. Embrace AI-driven changes, foster continuous learning, and build a future-ready workforce.
Read More - https://bit.ly/3VKly70
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving
What began over 115 years ago as a supplier of precision gauges to the automotive industry has evolved into being an industry leader in the manufacture of product branding, automotive cockpit trim and decorative appliance trim. Value-added services include in-house Design, Engineering, Program Management, Test Lab and Tool Shops.
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...DanBrown980551
This LF Energy webinar took place June 20, 2024. It featured:
-Alex Thornton, LF Energy
-Hallie Cramer, Google
-Daniel Roesler, UtilityAPI
-Henry Richardson, WattTime
In response to the urgency and scale required to effectively address climate change, open source solutions offer significant potential for driving innovation and progress. Currently, there is a growing demand for standardization and interoperability in energy data and modeling. Open source standards and specifications within the energy sector can also alleviate challenges associated with data fragmentation, transparency, and accessibility. At the same time, it is crucial to consider privacy and security concerns throughout the development of open source platforms.
This webinar will delve into the motivations behind establishing LF Energy’s Carbon Data Specification Consortium. It will provide an overview of the draft specifications and the ongoing progress made by the respective working groups.
Three primary specifications will be discussed:
-Discovery and client registration, emphasizing transparent processes and secure and private access
-Customer data, centering around customer tariffs, bills, energy usage, and full consumption disclosure
-Power systems data, focusing on grid data, inclusive of transmission and distribution networks, generation, intergrid power flows, and market settlement data
QA or the Highway - Component Testing: Bridging the gap between frontend appl...zjhamm304
These are the slides for the presentation, "Component Testing: Bridging the gap between frontend applications" that was presented at QA or the Highway 2024 in Columbus, OH by Zachary Hamm.
Session 1 - Intro to Robotic Process Automation.pdfUiPathCommunity
👉 Check out our full 'Africa Series - Automation Student Developers (EN)' page to register for the full program:
https://bit.ly/Automation_Student_Kickstart
In this session, we shall introduce you to the world of automation, the UiPath Platform, and guide you on how to install and setup UiPath Studio on your Windows PC.
📕 Detailed agenda:
What is RPA? Benefits of RPA?
RPA Applications
The UiPath End-to-End Automation Platform
UiPath Studio CE Installation and Setup
💻 Extra training through UiPath Academy:
Introduction to Automation
UiPath Business Automation Platform
Explore automation development with UiPath Studio
👉 Register here for our upcoming Session 2 on June 20: Introduction to UiPath Studio Fundamentals: https://community.uipath.com/events/details/uipath-lagos-presents-session-2-introduction-to-uipath-studio-fundamentals/
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
Discover the Unseen: Tailored Recommendation of Unwatched ContentScyllaDB
The session shares how JioCinema approaches ""watch discounting."" This capability ensures that if a user watched a certain amount of a show/movie, the platform no longer recommends that particular content to the user. Flawless operation of this feature promotes the discover of new content, improving the overall user experience.
JioCinema is an Indian over-the-top media streaming service owned by Viacom18.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...Fwdays
Direct losses from downtime in 1 minute = $5-$10 thousand dollars. Reputation is priceless.
As part of the talk, we will consider the architectural strategies necessary for the development of highly loaded fintech solutions. We will focus on using queues and streaming to efficiently work and manage large amounts of data in real-time and to minimize latency.
We will focus special attention on the architectural patterns used in the design of the fintech system, microservices and event-driven architecture, which ensure scalability, fault tolerance, and consistency of the entire system.
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...AlexanderRichford
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation Functions to Prevent Interaction with Malicious QR Codes.
Aim of the Study: The goal of this research was to develop a robust hybrid approach for identifying malicious and insecure URLs derived from QR codes, ensuring safe interactions.
This is achieved through:
Machine Learning Model: Predicts the likelihood of a URL being malicious.
Security Validation Functions: Ensures the derived URL has a valid certificate and proper URL format.
This innovative blend of technology aims to enhance cybersecurity measures and protect users from potential threats hidden within QR codes 🖥 🔒
This study was my first introduction to using ML which has shown me the immense potential of ML in creating more secure digital environments!
Must Know Postgres Extension for DBA and Developer during MigrationMydbops
Mydbops Opensource Database Meetup 16
Topic: Must-Know PostgreSQL Extensions for Developers and DBAs During Migration
Speaker: Deepak Mahto, Founder of DataCloudGaze Consulting
Date & Time: 8th June | 10 AM - 1 PM IST
Venue: Bangalore International Centre, Bangalore
Abstract: Discover how PostgreSQL extensions can be your secret weapon! This talk explores how key extensions enhance database capabilities and streamline the migration process for users moving from other relational databases like Oracle.
Key Takeaways:
* Learn about crucial extensions like oracle_fdw, pgtt, and pg_audit that ease migration complexities.
* Gain valuable strategies for implementing these extensions in PostgreSQL to achieve license freedom.
* Discover how these key extensions can empower both developers and DBAs during the migration process.
* Don't miss this chance to gain practical knowledge from an industry expert and stay updated on the latest open-source database trends.
Mydbops Managed Services specializes in taking the pain out of database management while optimizing performance. Since 2015, we have been providing top-notch support and assistance for the top three open-source databases: MySQL, MongoDB, and PostgreSQL.
Our team offers a wide range of services, including assistance, support, consulting, 24/7 operations, and expertise in all relevant technologies. We help organizations improve their database's performance, scalability, efficiency, and availability.
Contact us: info@mydbops.com
Visit: https://www.mydbops.com/
Follow us on LinkedIn: https://in.linkedin.com/company/mydbops
For more details and updates, please follow up the below links.
Meetup Page : https://www.meetup.com/mydbops-databa...
Twitter: https://twitter.com/mydbopsofficial
Blogs: https://www.mydbops.com/blog/
Facebook(Meta): https://www.facebook.com/mydbops/
In our second session, we shall learn all about the main features and fundamentals of UiPath Studio that enable us to use the building blocks for any automation project.
📕 Detailed agenda:
Variables and Datatypes
Workflow Layouts
Arguments
Control Flows and Loops
Conditional Statements
💻 Extra training through UiPath Academy:
Variables, Constants, and Arguments in Studio
Control Flow in Studio
2. Facts
• Developed at PUC Rio by Roberto
Lerusalimschy et al
• Born as a C/C++ extension language
• Incorporates most innovations of RAD
languages like Python, Ruby…
• Easily embeddable, lightweight and
efficient
• Totally free and open license
3. Chunks
• “a=1” in interactive mode
– each line in interactive mode is a chunck
• echo “a=1;b=2” > chunk.lua
– file chunk.lua is a chunk
• Running a chunk:
– “lua –lchunk” from command prompt
– “lua chunk.lua arg1 arg2” to pass command-line arguments
– dofile(“chunk.lua”) from within another chunk
6. Types and Values
• From within the interpreter:
– print(type(10))
• You can’t help trying these:
– print(type(nil))
– print(type(print)) --???!!!
7. Types and Values
• 6 built-in types:
– nil (nil)
– boolean (true | false)
– number (any real number, usual formats
allowed)
– string (any char sequence, 0 allowed!)
– table (more about these later)
– function (first-class values)
• 2 utility types:
– userdata
– thread
8. Tables
• From within the interpreter:
– t = {}
– t[“key”] = “value”; print(t[“key”])
– print(t[“otherkey”])
– t[1] = “first”; print(t[1]); print(t[“key”])
– print(t.key) --???!!!
– t = { key=“value”, otherkey=“first” }
– t = { key=“value”, 1=“first” } --???!!!
– t = { key=“value”, [1]=“first” }
– print(t.1) --???!!!
9. Arrays
• From within the interpreter:
– t[1] = ‘a’; t[2] = ‘b’; t[3] = ‘c’
– print(t[1] .. t[2] .. t[3])
– print(t[-1]) (got what you expected?)
– t[-1] = ‘z’
– print(t[-1])
– print(t) --???!!!
– print(unpack(t))
10. Functions
• From within the interpreter:
– function f ( a ) return a^2 end
– print(f(2))
• Functions are first-class values:
– t = {}
– t[“square”] = f
– print(t.square(2))
11. Some math…
• Arithmetic operators:
+ - * / -()
• Relational operators:
< > <= >= == ~=
• Logical operators:
and or not
– false and anything == false; true and
anything == anything
– nil and anything == false
– true or anything == true; false or anything
== anything
– nil or anything == anything
12. Assignments
• From within the interpreter:
– a = “Hi “ .. “there!”
– a, b = 10, a
– print(a, b)
– a, b = b, a
– print(a, b)
– a, b, c = 0
– print(a, b, c) --???!!!
13. Locals, blocks and scope
• From within the interpreter:
– a = 10
– local b = 2*a
– print(a, b) --???!!!
– do local b = 2*a; print(a,b) end
• What is a block?
– a chunk is a block
– a control sentence is a block
– a function body is a block
14. if then else
• From within the interpreter:
– if a < 0 then a = -a end
– if a == 1 then
– print(“first”)
– else
– if a < 0 then
– error(“outofrange”)
– else
– print(a)
– end
– end
15. while and repeat
• From within the interpreter:
– while a > 0 do
– print(a)
– a = a – 1
– end
– repeat
– print(a)
– a = a + 1
– until a > 10
16. for
• From within the interpreter:
– for i=1,10,2 do print(i) end
– pets = { “cat”, “dog”, “bunny” }
– for i,pet in pairs(pets) do print(i, pet) end
– for i,pet in ipairs(pets) do print(i, pet) end
– pets[“ops”] = “lion”
– for i,pet in pairs(pets) do print(i, pet) end
– for i,pet in ipairs(pets) do print(i, pet) end
17. break and return
• From within the interpreter:
– for i,pet in pairs(pets) do
– if pet==“lion” then break end
– end
– function findpet(name)
– for i,pet in pairs(pets) do
– if pet==name then return i,pet end
– end
– end
– print(findpet(“lion”))
18. Formal and actual args
• From within the interpreter:
– function f(a,b) print(a,b) end
– f()
– f(3)
– f(3,4)
– f(3,4,5)
– f{3,4,5} --???!!!
19. Returning multiple values
• From within the interpreter:
– function f(a,b) return a,b,5 end
– a = f(3,4); print(a)
– a,b = f(3,4); print(a,b)
– a,b,c = f(3,4); print(a,b,c)
– a,b,c,d = f(3,4); print(a,b,c,d)
– a,b,c,d = f(1,2) , f(3,4); print(a,b,c,d)
--???!!!
– t = { 1, 2 }; print(f(unpack(t)))
20. Variable number of args
• From within the interpreter:
– function f(a, b, …) print(a,b,unpack(arg))
end
– f(1)
– f(1,2)
– f(1,2,”Hi”, “there!”)
21. Named actual args
• From within the interpreter:
– function p(name, addr, age, gender)
– if age > 120 then error(“U’re kidding me”) end
– record = { name=name, addr=addr, age=age, gender=gender }
– end
– p(“Johnny”, “Cash”, “male”, 90) --???!!!
– function P(r) p(r.name, r.addr, r.age, r.gender) end
– P{name=“Johnny”,addr=“Cash”,gender=“male”,age=90}
22. Functions as first-class values
• function f(a,b) print(a,b) end
• syntactic sugar for:
– f = function (a,b) print(a,b) end
• some usages:
– table.sort(pets, function (a,b) return (a>b) end)
– square = {
– x = 0; y = 0; size = 20;
– draw = function() some code end
– }
23. Closures
• From within the interpreter:
– function newCounter ()
– local i = 0
– return function() i=i+1; return i end
– end
– c1 = newCounter()
– c2 = newCounter()
– print(c1(), c1(), c1())
– print(c2(), c2())
24. Proper tail calls
• Check this C code:
– int f ( char* state ) {
– if (strcmp(state, “exit”))
– return(0);
– return f(state);
– }
– int result = f(“ooops”);
25. Iterators
• From within the interpreter:
– function words ( filename )
– local file = io.open(filename)
– local line = file:read()
– local i = nil
– return function ()
– local b, e
– while not b do
– if not line then return nil end
– b,e = string.find(line, "[%w_]+", i)
– if b then
– i = e + 1; return string.sub(line, b, e)
– else
– i = nil; line = file:read()
– end
– end
– end
– end
–
– for word in words("chunk.lua") do print(word) end
26. Loading libraries
• Loading Lua libraries:
– require “mypackage.mylib”
• Loading shared libraries:
– local path =
“/usr/local/lua/lib/libluasocket.so”
– local f = loadlib(path, “luaopen_socket”)
– f() -- opens the library
27. Errors
• From within the interpreter:
– file = assert(io.open(‘chunk.lua’, ‘r’))
• assert(chunk,msg) == if not chunk then
error(msg)
• From within the interpreter:
– local status, err =
– pcall(P{name=“Johnny”,address=“Cash”,age=150,
gender=“male”})
– if not status then print(err) end
28. Coroutines
• From within the interpreter:
– co = coroutine.create(function()
– for i=1,10 do
– print("co", i)
– coroutine.yield()
– end
– end)
–
– coroutine.resume(co)
– coroutine.resume(co)
– coroutine.resume(co)
29. Metatables
• From within the interpreter:
– Complex = {}
– function Complex.new (c)
– setmetatable(c, Complex); return c
– end
– function Complex.__add (a,b)
– return Complex.new{r=a.r+b.r, i=a.i+b.i}
– end
– c = Complex.new{r=1,i=2} +
Complex.new{r=3,i=4}
– print(unpack(c))
31. Polymorphism
• From within the interpreter:
– print(c)
– function Complex.__tostring(c)
– return tostring(c.r) .. ‘+’ .. tostring(c.i)
.. ‘i’
– end
– print(c)
32. Inheritance
• From within the interpreter:
– Phone = {}
– Phone.keypad = {[1]=“1”, [2]=“2”}
– function Phone.dial ( keys ) print(keys) end
– CarPhone = {}
– CarPhone.mike = io
– CarPhone.dir = { Johnny = “112”, Cash = “211” }
– function CarPhone.voice_dial ()
– CarPhone.dial(CarPhone.dir[CarPhone.mike.read()])
– end
33. Inheritance
• From within the interpreter:
– CarPhone.voice_dial() ???!!!
– Phone.__index = Phone
– setmetatable(CarPhone, Phone)
– CarPhone.voice_dial()
– Phone.speaker = io
– CarPhone.speaker.write(“Beeeeeeeeep”)
34. Overloading
• From within the interpreter:
– CellPhone = {
– dial = function ( keys ) error(“no link”)
end
– }
– setmetatable(CellPhone, Phone)
– CellPhone.dial(“112”)
• There is no argument-based
overloading!
35. Metamethods
• List of metamethods:
– add (+)
– sub (-)
– mul (*)
– div (/)
– mod (%)
– pow (^)
– unm (-)
– concat (..)
– len (#)
– eq (=)
– lt (<)
– le (<=)
– index ([])
– newindex
– call (())
36. The environment
• From within the interpreter:
– print(_G._G == _G) ???!!!
– for gv in pairs(_G) do print(gv) end
– for obj in pairs(_G) do
– if string.find(obj, “Phone$”) then
– _G[obj].dial(“112”)
– end
– end
– setmetatable(_G, {
– __newindex = function(_,gv) error(“read only!”) end,
– })
– newglobal = “oopss”
37. More environments
• From within the interpreter:
– ctx = { ignore_case=true }
– function my_find ( string, regexp )
– if ctx and ctx.ignore_case then
– return string.find(string.lower(string), regexp)
– else
– return string.find(string, regexp)
– end
– end
– print(my_find(“Hi there!”, “hi”))
– do
– local myG = { ctx = {} }
– setmetatable(myG, {__index=_G})
– setfenv(my_find, myG)
– end
– print(my_find(“Hi there!”, “hi”))
– setfenv(my_find, _G)
38. OO Programming
• From within the interpreter:
– function Phone:new (obj)
– obj = obj or {}
– setmetatable(obj, self)
– self.__index = self
– return obj
– end
– my_phone = Phone:new()
– my_phone:dial(“112”) --???!!!
39. Metatables in OO Programming
Key Value
Key Value
__tostring
__newindex
__index
new
…
obj
Phone
…
setmetatable(obj,self)
…
40. C API: the stack
• C to Lua:
– void lua_pushnil
– void lua_pushboolean
– void lua_pushnumber
– void lua_pushstring
– void lua_pushlstring
• Lua to C:
– int lua_toboolean
– double lua_tonumber
– const char* lua_tostring
– size_t lua_strlen
– void lua_gettable
– void lua_settable
C running image
Data segment
Code segment
stack
C code Lua lib
41. C API: other stack functions
– lua_open to create a Lua state
– luaL_loadfile to read a Lua script into memory
– lua_pcall to run a Lua chunk in protected mode
– lua_getglobal to read lua global environment
– lua_setglobal to write lua global environment
– lua_pop to remove a value from the stack
– lua_newtable to create a new table on the stack
– lua_close to end a running state
42. C API: the stack from the other side
• Pre-C to Lua:
– void
lua_pushcfunction
• C to Lua the right
way™:
– struct luaL_reg
– void luaL_openlib
• Lua to C the right
way™:
– loadlib()
C running image
Data segment
Code segment
stack
C code Lua lib
43. C API: Example
• #include <dirent.h>
• #include <errno.h>
• static int l_dir (lua_State *L) {
• DIR *dir; struct dirent *entry; int i;
• const char *path = luaL_checkstring(L, 1);
• /* open directory */
• dir = opendir(path);
• if (dir == NULL) { /* error opening the directory? */
• lua_pushnil(L); /* return nil and ... */
• lua_pushstring(L, strerror(errno)); /* error message */
• return 2; /* number of results */
• }
• /* create result table */
• lua_newtable(L);
• i = 1;
• while ((entry = readdir(dir)) != NULL) {
• lua_pushnumber(L, i++); /* push key */
• lua_pushstring(L, entry->d_name); /* push value */
• lua_settable(L, -3);
• }
• closedir(dir);
• return 1; /* table is already on top */
• }
46. Example: application configuration
• In file “app.conf”:
– function dbIterator ( table )
– local dbConn = lua.sql.connect(db_url)
– local cursor = dbConn.execute(“SELECT * FROM “ .. table)
– return function() return cursor.next() end
– end
–
– for dbRule in dbIterator do Rule(dbRule) end
–