Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Lua: Small embeddable scripting language with co-routines

News

Recommended Books

Recommended Links

Reference

Articles

Tutorials

Introductory Courses

FAQs  

Prototype-based programming

Jscript

RegEx

Script Archives

Jscript Debugger

WSH

Engines

Javascript in Lotus Notes Netscape Debugger
DOM Model Advanced Cookies Outliners,
Contents Generators
Debugging Quotes History Humor Etc
 

As in all engineering pursuits, choosing between a compiled language and an interpreted language means measuring the pros and cons of each in context, weighing the trade-offs, and accepting compromises.

An introduction to  Lua programming can be found in the book:

Programming in Lua
by Roberto Ierusalimschy
Lua.org, third edition, January 2013
ISBN 859037985X (also available as e-book)

This book is now in the third edition covering Lua 5.2. The first edition which cover Lua 5.0 is available online; it is still largely relevant. 

Martin Streicher wrote a good intro for IBM Developer Works (Embeddable scripting with Lua): 

Lua offers high-level abstraction without losing touch with the hardware

Level: Introductory

Martin Streicher ([email protected]), Editor-in-Chief, Linux Magazine

28 Apr 2006

Compiled programming languages and scripting languages each have unique advantages, but what if you could use both to create rich applications? Lua is an embeddable scripting language that is small, fast, and very powerful. Before you create yet another configuration file or resource format (and yet another parser to accompany it), try Lua.
Compiled programming languages and scripting languages each have unique advantages, but what if you could use both to create rich applications? Lua is an embeddable scripting language that is small, fast, and very powerful. Before you create yet another configuration file or resource format (and yet another parser to accompany it), try Lua.

The Lua programming language is a small scripting language specifically designed to be embedded in other programs. Lua's C API allows exceptionally clean and simple code both to call Lua from C, and to call C from Lua. This allows developers who want a convenient runtime scripting language to easily implement the basic API elements needed by the scripting language, then use Lua code from their applications. This article introduces the Lua language as a possible tool for simplifying common development tasks, and discusses some of the reasons to embed a scripting language in the first place.

While interpreted programming languages such as Perl, Python, PHP, and Ruby are increasingly favored for Web applications -- and have long been preferred for automating system administration tasks -- compiled programming languages such as C and C++ are still necessary. The performance of compiled programming languages remains unmatched (exceeded only by the performance of hand-tuned assembly), and certain software -- including operating systems and device drivers -- can only be implemented efficiently using compiled code. Indeed, whenever software and hardware need to mesh seamlessly, programmers instinctively reach for a C compiler: C is primitive enough to get "close to the bare metal" -- that is, to capture the idiosyncrasies of a piece of hardware -- yet expressive enough to offer some high-level programming constructs, such as structures, loops, named variables, and scope.

However, scripting languages have distinct advantages, too. For example, after a language's interpreter is successfully ported to a platform, the vast majority of scripts written in that language run on the new platform unchanged -- free of dependencies such as system-specific function libraries. (Think of the many DLL files of the Microsoft® Windows® operating system or the many libcs of UNIX® and Linux®.) Additionally, scripting languages typically offer higher-level programming constructs and convenience operations, which programmers claim boost productivity and agility. Moreover, programmers working in an interpreted language can work faster, because the compilation and link steps are unnecessary. The "code, build, link, run" cycle of C and its ilk is reduced to a hastened "script, run."

Lua novelties

Like every scripting language, Lua has its own peculiarities:

Find more examples of Lua code in Programming in Lua and in the Lua-users wiki (for links, see the Resources section below).

 

Mixing the best of both worlds

But what if you could enjoy the best of both worlds: close to bare metal performance and high-level, powerful abstractions? Better yet, what if you could optimize algorithms and functions that are processor intensive and system dependent as well as separate logic that's system independent and highly susceptible to changes in requirements?

Balancing the need for high-performance code and high-level programming is the purview of Lua, an embeddable scripting language. Applications that include Lua are a combination of compiled code and Lua scripts. Compiled code can drop to the metal when necessary, yet can call Lua scripts to manipulate complex data. And because the Lua scripts are separate from the compiled code, you readily and separately revise the scripts. With Lua, the development cycle is more akin to "Code, Build, Run, Script, Script, Script...".

For example, the Lua Web site "Uses" page (see Resources) lists several mass-market computer games, including World of Warcraft and (the home console version of arcade classic) Defender, that integrate Lua to run everything from the user interface to the artificial intelligence of foes. Other applications of Lua include an extension mechanism for the popular Linux software update tool apt-rpm and the control of the "Crazy Ivan" Robocup 2000 champion. Many of the testimonials on that page laud Lua's small size and excellent performance.

Getting started with Lua

Lua version 5.0.2 was the current version at the time of this writing, although version 5.1 was released recently. You can download Lua as source code from lua.org, and you can find a variety of pre-built binaries at the Lua-users wiki (see Resources for links). The entire Lua 5.0.2 core, including the standard libraries and the Lua compiler, is less than 200KB in size.

If you use Debian Linux, you can install Lua 5.0 quickly and easily by running this command:

# apt-get install lua50

 

as the superuser. All the examples shown here were run on Debian Linux "Sarge" using Lua 5.0.2 and the 2.4.27-2-686 Linux kernel.

After you've installed Lua on your system, give the stand-alone Lua interpreter a try. (All Lua applications must be embedded in a host application. The interpreter is simply a special kind of host, useful for development and debugging.) Create a file called factorial.lua, and enter the lines:

-- defines a factorial function
function fact (n)
  if n == 0 then
    return 1
  else
    return n * fact(n-1)
  end
end

print("enter a number:")
a = io.read("*number")
print(fact(a))

 

The code in factorial.lua -- more specifically, any sequence of Lua statements -- is called a chunk, as described in the Lua novelties section above. To execute the chunk you just created, run the command lua factorial.lua:

$ lua factorial.lua
enter a number:
10
3628800
 


Or, as in other interpreted languages, you can add a "shebang" (#!) line at the top of the script, make the script executable, and then run the file as a stand-alone command:

$ (echo '#! /usr/bin/lua'; cat factorial.lua) > factorial 
$ chmod u+x factorial
$ ./factorial
enter a number:
4
24

 

The Lua language

Lua has many of the conveniences found in a modern scripting language: scope, control structures, iterators, and a host of standard libraries for processing strings, emitting and collecting data, and performing mathematical operations. A complete description of the Lua language is in the Lua 5.0 Reference Manual (see Resources).

In Lua, only values have a type, but variables are dynamically typed. There are eight fundamental types (of values) in Lua: nil, boolean, number, string, function, thread, table, and userdata. The first six types are largely self-descriptive (see the Lua novelties section above for the exceptions); the last two need some explanation.

Lua tables

Tables are the catch-all data structure in Lua. Indeed, tables are the only data structure in Lua. You can use a table as an array, a dictionary (also called a hash or an associative array), a tree, a record, and so on.

Unlike other programming languages, the contents of a Lua table need not be homogeneous: The table can include any combination of types and can contain a mix of array-like elements and dictionary-like elements. Moreover, any Lua value -- including a function or another table -- can serve as a dictionary element key.

To explore tables, start the Lua interpreter and type the lines shown in bold in Listing 1.


Listing 1. Experimenting with Lua tables
$ lua
> -- create an empty table and add some elements
> t1 = {}
> t1[1] = "moustache"
> t1[2] = 3
> t1["brothers"] = true

> -- more commonly, create the table and define elements
> all at once
> t2 = {[1] = "groucho", [3] = "chico", [5] = "harpo"}
> t3 = {[t1[1]] = t2[1], accent = t2[3], horn = t2[5]}
> t4 = {}
> t4[t3] = "the marx brothers"
> t5 = {characters = t2, marks = t3}
> t6 = {["a night at the opera"] = "classic"}

> -- make a reference and a string
> i = t3
> s = "a night at the opera"

> -- indices can be any Lua value
> print(t1[1], t4[t3], t6[s])
moustache   the marx brothers classic

> -- the phrase table.string is the same as table["string"]
> print(t3.horn, t3["horn"])
harpo   harpo

> -- indices can also be "multi-dimensional"
> print (t5["marks"]["horn"], t5.marks.horn)
harpo   harpo

> -- i points to the same table as t3
> = t4[i]
the marx brothers

> -- non-existent indices return nil values
> print(t1[2], t2[2], t5.films)
nil     nil     nil

>  -- even a function can be a key 
> t = {}
> function t.add(i,j)
>> return(i+j)
>> end
> print(t.add(1,2))
3
> print(t['add'](1,2))
3
>  -- and another variation of a function as a key 
> t = {}
> function v(x)
>> print(x)
>> end
> t[v] = "The Big Store"
> for key,value in t do key(value) end
The Big Store

As you might expect, Lua also provides a fair number of iterator functions to process tables. The global variable table provides the functions (yes, Lua packages are just tables, too). Some functions, like table.foreachi(), expect a contiguous range of integer keys starting at 1 (the numeral one):
> table.foreachi(t1, print)
1 moustache
2 3

Others, such as table.foreach(), iterate over an entire table:

> table.foreach(t2,print)
1       groucho
3       chico
5       harpo
> table.foreach(t1,print)
1       moustache
2       3
brothers        true

 

While some iterators are optimized for integer indices, all simply process (key, value) pairs.

For fun, create a table, t, with elements {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="www.lua.org"}, and run table.foreach(t, print) and table.foreachi(t, print).

Userdata

Because Lua is intended to be embedded in a host application written in a language such as C or C++ and is intended to cooperate with the host application, data must be shared between the C environment and Lua. As the Lua 5.0 Reference Manual says, the userdata type allows "arbitrary C data to be stored in Lua variables." You can think of userdata as an array of bytes -- bytes that might represent a pointer, a structure, or a file in the host application.

The contents of userdata originates with C, so it cannot be modified in Lua. Of course, because the userdata originates in C, there are no pre-defined operations for userdata in Lua. However, you can create operations that operate on userdata using another Lua mechanism, called metatables.

Metatables

Because tables and userdata are so flexible, Lua permits you to overload operations for objects of either type. (You cannot overload the six other types.) A metatable is a (normal) Lua table that maps standard operations to custom functions that you provide. The keys of the metatable are called events; the values (in other words, the functions) are called metamethods.

The functions setmetatable() and getmetatable() modify and query an object's metatable, respectively. Each table and userdata object can have its own metatable.

For example, one event is __add, for addition. Can you deduce what this chunk does?

-- Overload the add operation
-- to do string concatenation
--
mt = {}

function String(string)
  return setmetatable({value = string or ''}, mt)
end

-- The first operand is a String table
-- The second operand is a string
-- .. is the Lua concatenate operator
--
function mt.__add(a, b)
  return String(a.value..b)
end

s = String('Hello')
print((s + ' There ' + ' World!').value )

 

This chunk emits the following text:

Hello There World!

The function String() takes a string, string, wraps it in a table ({value = s or ''}), and assigns the metatable mt to the table. Function mt.__add() is a metamethod that appends the string b to the string found in a.value b times. The line print((s + ' There ' + ' World!').value ) invokes the metamethod twice.

__index is another event. The metamethod for __index is called whenever a key doesn't exist in a table. Here's an example that "memoizes," or remembers, the value of a function:

-- code courtesy of Rici Lake, [email protected]
function Memoize(func, t)
  return setmetatable(
     t or {},
    {__index =
      function(t, k)
        local v = func(k);
        t[k] = v;
        return v;
        end
    }
  )
end

COLORS = {"red", "blue", "green", "yellow", "black"}
color = Memoize(
  function(node)
    return COLORS[math.random(1, table.getn(COLORS))]
    end
)

 

Put the code into the Lua interpreter, and then type print(color[1], color[2], color[1]). You should see something like blue black blue.

This code, given a key, node, looks up the color for the node. If it doesn't exist, the code permanently assigns node a new, randomly chosen color. Otherwise, the node's assigned color is returned. In the former case, the __index metamethod is executed once to assign a color. The latter case is a simple and fast hash lookup.

The Lua language offers many other powerful features, and all of them are well documented. But in case you ever run into trouble or want to talk to a wizard, head over to the Lua Users Chat Room IRC Channel (see Resources) for some very enthusiastic support.

Embed and extend

Beyond Lua's simple syntax and powerful table structure, Lua's real power is evident when mixing it with a host language. As has been intimated, Lua scripts can extend the host language's own capabilities. But the reciprocal is true as well: The host language can simultaneously extend Lua. C functions can call Lua functions and vice versa, for example.

At the heart of the symbiotic relationship between Lua and its host language is a virtual stack. The virtual stack -- like a real stack -- is a last in-first out (LIFO) data structure that temporarily stores function arguments and function results. To make a call from Lua to its host language and vice versa, the caller pushes values onto the stack and calls the target function; the callee pops the arguments (verifying the type and value of each argument, of course), processes the data, and pushes the result on the stack. When control returns to the caller, the caller extracts the return values from the stack.

Virtually all the C application program interface (API) for Lua operations operate through the stack. The stack can hold any Lua value; however, the type of the value must be known to the caller and callee, and specific functions push and pop each type from the stack (such as lua_pushnil() and lua_pushnumber().

Listing 2 shows a simple C program (taken from Chapter 24 of the Programming in Lua book cited in Resources) that implements a minimal but functional Lua interpreter.


Listing 2. A simple Lua interpreter
 1 #include <stdio.h>
 2 #include <lua.h>
 3 #include <lauxlib.h>
 4 #include <lualib.h>
 5
 6 int main (void) {
 7   char buff[256];
 8   int error;
 9   lua_State *L = lua_open();   /* opens Lua */
10   luaopen_base(L);             /* opens the basic library */
11   luaopen_table(L);            /* opens the table library */
12   luaopen_io(L);               /* opens the I/O library */
13   luaopen_string(L);           /* opens the string lib. */
14   luaopen_math(L);             /* opens the math lib. */
15
16   while (fgets(buff, sizeof(buff), stdin) != NULL) {
17     error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
18             lua_pcall(L, 0, 0, 0);
19     if (error) {
20       fprintf(stderr, "%s", lua_tostring(L, -1));
21       lua_pop(L, 1);  /* pop error message from the stack */
22     }
23   }
24
25   lua_close(L);
26   return 0;
27 }
 

Lines 2 through 4 include the Lua standard functions, several convenience functions that are used in all Lua libraries, and functions to open libraries, respectively. Line 9 creates a Lua state. All states are initially empty; you add libraries of functions to the state using luaopen_...(), as shown in Lines 10 through 14.

Line 17 and luaL_loadbuffer() take the input from stdin as a chunk and compile it, placing the chunk on the virtual stack. Line 18 pops the chunk from the stack and executes it. If an error occurs during execution, a Lua string is pushed on the stack. Line 20 accesses the top of the stack (the top of the stack has an index of -1) as a Lua string, prints the message, and then removes the value from the stack.

Using the C API, your application can also "reach" into the Lua state to extract information. This snippet grabs two global variables from the Lua state:

..
if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0))
  error(L, "cannot run configuration file: %s", lua_tostring(L, -1));

lua_getglobal(L, "width");
lua_getglobal(L, "height");
..
width = (int) lua_tonumber(L, -2);
height = (int) lua_tonumber(L, -1);
..

Again, notice that the stack enables the transfer. Calling any Lua function from C is similar to this code:

If a Lua function returns n values, the first value is at location -n in the stack, and the last value is at position -1.

The inverse -- calling a C function from Lua -- is similar. If your operating system supports dynamic loading, Lua can load and call functions on demand. (In operating systems where static loading is a necessity, extending the Lua engine to call a C function requires you to rebuild Lua.)

Lua is out of this world

Lua is an incredibly easy language to pick up, but its simple syntax disguises its power: The language supports objects (which are similar to Perl's), metatables make its table type quite malleable, and the C API allows great integration and extension between scripts and the host language. Lua has been hosted in the C, C++, C#, Java™, and Python languages.

Before you create yet another configuration file or resource format (and yet another parser to accompany it), try Lua. The Lua language -- like its community -- is robust, inventive, and ready to help.

History

Lua was created in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes, members of the Computer Graphics Technology Group at PUC-Rio, the Pontifical University of Rio de Janeiro, in Brazil. Versions of Lua prior to version 5.0 were released under a license similar to the BSD license. From version 5.0 onwards, Lua has been licensed under the MIT License.

Some of its closest relatives include Icon for its design and Python for its ease of use by non-programmers. In an article published in Dr. Dobb's Journal, Lua's creators also state that Lisp and Scheme with their single, ubiquitous data structure mechanism (the list) were a major influence on their decision to develop the table as the primary data structure of Lua.[1]

Lua has been used in many applications, both commercial and non-commercial. See the Applications section for a detailed list. Lua has been used to program homebrew applications for the PlayStation Portable and the Nintendo DS.

Features

Lua is commonly described as a "multi-paradigm" language, providing a small set of general features that can be extended to fit different problem types, rather than providing a more complex and rigid specification to match a single paradigm. Lua, for instance, does not contain explicit support for inheritance, but allows it to be implemented relatively easily with metatables. Similarly, Lua allows programmers to implement namespaces, classes, and other related features using its single table implementation; first class functions allow the employment of many powerful techniques from functional programming; and full lexical scoping allows fine-grained information hiding to enforce the principle of least privilege.

In general, Lua strives to provide flexible meta-features that can be extended as needed, rather than supply a feature-set specific to one programming paradigm. As a result, the base language is light - in fact, the full reference interpreter is only about 150kB compiled - and easily adaptable to a broad range of applications.

Lua is a dynamically typed language intended for use as an extension or scripting language, and is compact enough to fit on a variety of host platforms. It supports only a small number of atomic data structures such as boolean values, numbers (double-precision floating point by default), and strings. Typical data structures such as arrays, sets, hash tables, lists, and records can be represented using Lua's single native data structure, the table, which is essentially a heterogeneous map.

Lua has no built-in support for namespaces and object-oriented programming. Instead, metatable and metamethods are used to extend the language to support both programming paradigms in an elegant and straight-forward manner.

Lua implements a small set of advanced features such as higher-order functions, garbage collection, first-class functions, closures, proper tail calls, coercion (automatic conversion between string and number values at run time), coroutines (cooperative multitasking) and dynamic module loading.

By including only a minimum set of data types, Lua attempts to strike a balance between power and size.

Example code

The classic hello world program can be written as follows:

print "Hello, World!" The factorial is an example of a recursive function:

function factorial(n) if n == 0 then return 1 end return n * factorial(n - 1) -- A comment in Lua starts with a double-hyphen end -- and runs to the end of the line

Lua's treatment of functions as first class variables is shown in the following example, where the print function's behavior is modified:

do local oldprint = print -- Store current print function as old print print = function(s) -- Redefine print function if s == "foo" then oldprint("bar") else oldprint(s) end end end

Any future calls to "print" will now be routed through the new function, and thanks to Lua's lexical scoping, the old print function will only be accessible by the new, modified print.

Lua also supports closures, as demonstrated below:

function makeaddfunc(x) -- Return a new function that adds x to the argument return function(y) -- When we refer to the variable x, which is outside of the current -- scope and whose lifetime is shorter than that of this anonymous -- function, Lua creates a closure. return x + y end end plustwo = makeaddfunc(2) print(plustwo(5)) -- Prints 7

A new closure for the variable x is created every time makeaddfunc is called, so that the anonymous function returned will always access its own x parameter. The closure is managed by Lua's garbage collector, just like any other object.

Extensible semantics is a key feature of Lua, and the "metatable" concept allows Lua's tables to be customized in powerful and unique ways. The following example demonstrates an "infinite" table. For any n, fibs[n] will give the nth Fibonacci number using dynamic programming.

fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2]. setmetatable(fibs, { -- Give fibs some magic behavior. __index = function(name, n) -- Call this function if fibs[n] does not exist. name[n] = name[n - 1] + name[n - 2] -- Calculate and memoize fibs[n]. return name[n] end })

Tables

Tables are the most important data structure (and, by design, the only complex data structure) in Lua, and are the foundation of all user-created types.

The table is a collection of key and data pairs (known also as hashed heterogeneous associative array), where the data is referenced by key. The key (index) can be of any data type except nil. An integer key of 1 is considered distinct from a string key of "1".

Tables are created using the {} constructor syntax: a_table = {} -- Creates a new, empty table

Tables are always passed by reference: a_table = {x = 10} -- Creates a new table, with one associated entry. The string x mapping to the number 10. print(a_table["x"]) -- Prints the value associated with the string key, in this case 10. b_table = a_table a_table["x"] = 20 -- The value in the table is been changed to 20. print(a_table["x"]) -- Prints 20. print(b_table["x"]) -- Prints 20, because a_table and b_table both refer to the same table.

Table as structure

Tables are often used as structures (or objects) by using strings as keys. Because such use is very common, Lua features a special syntax for accessing such fields. Example: point = { x = 10, y = 20 } -- Create new table print(point["x"]) -- Prints 10 print(point.x) -- Has exactly the same meaning as line above

Table as array

By using a numerical key, the table resembles an array data type. Lua arrays are 1-based; the first index is 1 rather than 0 as it is for many programming languages (though an explicit index of 0 is allowed).

A simple array of strings: array = { "a", "b", "c", "d" } -- Indices are assigned automatically. print(array[2]) -- Prints "b". Automatic indexing in Lua starts at 1. print(#array) -- Prints 4. # is the length operator for tables and strings. array[0] = "z" ''-- Zero is a legal index. print(#array) ''-- Still prints 4, as Lua arrays are 1-based.

An array of objects: function Point(x, y) -- "Point" object constructor return { x = x, y = y } -- Creates and returns a new object (table) end array = { Point(10, 20), Point(30, 40), Point(50, 60) } -- Creates array of points print(array[2].y) -- Prints 40

Object-oriented programming

Although Lua does not have a built-in concept of classes, the language is powerful enough to easily implement them using two language features: first-class functions and tables. By simply placing functions and related data into a table, an object is formed. Inheritance (both single and multiple) can be implemented via the "metatable" mechanism, telling the object to lookup nonexistent methods and fields in parent object(s).

There is no such concept as "class" with these techniques, rather "prototypes" are used as in Self programming language or Javascript. New objects are created either with a factory method (that constructs new objects from scratch) or by cloning an existing object.

Lua provides some syntactic sugar to facilitate object orientation. To declare member functions inside a prototype table, you can use function table:func(args), which is equivalent to function table.func(self, args). Calling class methods also makes use of the colon: object:func(args) is equivalent to object.func(object, args).

Creating a basic vector object:

Vector = { } -- Create a table to hold the class methods function Vector:new(x, y, z) -- The constructor function object = { x = x, y = y, z = z } setmetatable(object, { -- Overload the index event so that fields not present within the object are -- looked up in the prototype Vector table __index = Vector }) return object end function Vector:mag() -- Declare another member function, to determine the magnitude of the vector -- Reference the implicit object using self return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) end local vec = Vector:new(0, 1, 0) -- Create a vector print(vec:mag()) -- Call a member function using ":" print(vec.x) -- Access a member variable using "."

Internals

Lua programs are not interpreted directly from the textual Lua file, but are compiled into bytecode which is then run on the Lua virtual machine. The compilation process is typically transparent to the user and is performed during run-time, but it can be done offline in order to increase performance or reduce the memory footprint of the host environment by leaving out the compiler.

This example is the bytecode listing of the factorial function described above (in Lua 5.1.1):

function <factorial.lua:1,6> (10 instructions, 40 bytes at 003D5818) 1 param, 3 slots, 0 upvalues, 1 local, 3 constants, 0 functions 1 [2] EQ 0 0 -1 ; - 0 2 [2] JMP 2 ; to 5 3 [3] LOADK 1 -2 ; 1 4 [3] RETURN 1 2 5 [5] GETGLOBAL 1 -3 ; factorial 6 [5] SUB 2 0 -2 ; - 1 7 [5] CALL 1 2 2 8 [5] MUL 1 0 1 9 [5] RETURN 1 2 10 [6] RETURN 0 1

There is also a free, third-party just-in-time compiler for the latest version (5.1) of Lua, called LuaJIT. It's very small (under 32kB of additional code) and can often improve the performance of a Lua program significantly. [2]

C API

Lua is intended to be embedded into other applications, and accordingly it provides a robust, easy to use C API. The API is divided into two parts: the Lua core [3], and the Lua auxiliary library [4].

The Lua API is fairly straightforward because its unique design eliminates the need for manual reference management in C code, unlike Python's API. The API, like the language, is minimalistic. Advanced functionality is provided by the auxiliary library, which consists largely of preprocessor macros which make complex table operations more palatable.

The Lua Stack

The Lua API makes extensive use of a global stack which is used to pass parameters to and from Lua and C functions. Lua provides functions to push and pop most simple C data types (integers, floats, etc.) to and from the stack, as well as functions for manipulating tables through the stack. The Lua stack is somewhat different from a traditional stack; the stack can be indexed directly, for example. Negative indices indicate offsets from the top of the stack (for example, -1 is the last element), while positive indices indicate offsets from the bottom.

Marshalling data between C and Lua functions is also done using the stack. To call a Lua function, arguments are pushed onto the stack, and then the lua_call is used to call the actual function. When writing a C function to be directly called from Lua, the arguments are popped from the stack.

Special Tables

The C API also provides several special tables, located at various "pseudo-indices" in the Lua stack. At LUA_GLOBALSINDEX is the globals table, _G from within Lua, which is the main namespace. There is also a registry located at LUA_REGISTRYINDEX where C programs can store Lua values for later retrieval.

Extension Modules

It is possible to write extension modules using the Lua API. Extension modules are shared objects which can be used to extend the functionality of the interpreter by providing native facilities to Lua scripts. Lua scripts may load extension modules using require [5].
Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Dec 07, 2015] Scripted window actions on Ubuntu with Devilspie 2

On this page
•What is LUA?
•Installation.
•Config and Scripting. •Sample Scripts.
•Sript Commands.

•Links

Devilspie2 is a program that detects windows as they are created, and performs scripted actions on them. The scripts are written in LUA, allowing a great deal of customization. This tutorial will show you the installation of Devilspie 2 on Ubuntu 14.04 and give you a introduction into Devilspie scripting.


What is LUA?

Lua is a powerful, fast, lightweight, embeddable scripting language. Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping.

For futher infomation visit: http://www.lua.org/

Embed Lua for scriptable apps

The Lua programming language is a small scripting language specifically designed to be embedded in other programs. Lua&apos;s C API allows exceptionally clean and simple code both to call Lua from C, and to call C from Lua. This allows developers who want a convenient runtime scripting language to easily implement the basic API elements needed by the scripting language, then use Lua code from their applications. This article introduces the Lua language as a possible tool for simplifying common development tasks, and discusses some of the reasons to embed a scripting language in the first place.

Recommended Links

The Programming Language Lua

Lua (programming language) - Wikipedia, the free encyclopedia

computing, the Lua (pronounced LOO-ah, or /'lua/ in IPA) programming language is a lightweight, reflective, imperative and procedural language, designed as a scripting language with extensible semantics as a primary goal. The name is derived from the Portuguese word for moon.

Bindings to Other Languages

Applications

Lua, as a compiled binary, is very small by code standards. Coupled with it being relatively fast and having a very lenient license, it has gained a following among game developers for providing a viable scripting interface.

Games

Other applications

A list of projects known to use Lua is located at Lua.org.

Books

Trivia

External links


Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 12, 2019