CGILua
Building Web Scripts with Lua

Introduction

CGILua uses Lua as a server-side scripting language for creating dynamic Web pages. Both pure Lua Scripts and Lua Pages (LP) are supported by CGILua. A Lua Script is essentially a Lua program that creates the whole contents of a web page and returns it to the client. A Lua Page is a conventional markup text (HTML, XML etc) file that embeds Lua code using some special tags. Those tags are processed by CGILua and resulting page is returned to the client.

Lua Scripts and Lua Pages are equally easy to use, and choosing one of them basically depends on the characteristics of the resulting page. While Lua Pages are more convenient for the separation of logic and format, Lua Scripts are more adequate for creating pages that are simpler in terms of its structure, but require a more significative amount of internal processing.

Allowing these two methods to be intermixed, CGILua provides Web applications developers with great flexibility when both requirements are present. For a detailed description of both scripting methods and some examples of their use see Lua Scripts and Lua Pages.

CGILua architecture is divided in two layers. The lower level is represented by the Server API (SAPI) and the higher level is represented by the CGILua API itself. SAPI is the interface between the web server and the CGILua API, so it needs to be implemented for each web server and launching method used.

CGILua and the CGILua API are implemented using only SAPI and are totally portable between launchers and their supported web servers. This way any Lua Script or Lua Page could be used by any launcher.

Installation

CGILua follows the package model for Lua 5.1, therefore it should be "installed". Refer to Compat-5.1 configuration section about how to install the module properly.

Configuration

CGILua 5.0 offers a single configuration file, called config.lua and a set of functions to alter the default CGILua configuration. This file can be placed elsewhere in the LUA_PATH to make easier to upgrade CGILua without overwriting your config.lua.

Some of the uses of config.lua are:

Script Handlers
You can add new CGILua handlers using cgilua.addscripthandler (see also cgilua.buildplainhandler and cgilua.buildprocesshandler for functions that build simple handlers).
POST Data Sizes
You can change the POST data size limits using cgilua.setmaxinput and cgilua.setmaxfilesize.
Opening and Closing Functions
You can add your functions to the life cycle of CGILua using cgilua.addopenfunction and cgilua.addclosefunction. These functions are executed just before and after the script execution, even when an error occurs in the script processing.

Error Handling

There are three functions for error handling in CGILua:

The function cgilua.seterrorhandler defines the error handler, a function called by Lua when an error has just occurred. The error handler has access to the execution stack before the error is thrown so it can build an error message using stack information. Lua also provides a function to do that: debug.traceback.

The function cgilua.seterroroutput defines the function that decides what to do with the error message. It could be sent to the client's browser, written to a log file or sent to an e-mail address (with the help of LuaSocket or LuaLogging for example).

The function cgilua.errorlog is provided to write directly to the http server error log file.

Lua Scripts

Lua Scripts are text files containing valid Lua code. This style of usage adopts a more "raw" form of web programming, where a program is responsible for the entire generation of the resulting page. Lua Scripts have a default .lua extension.

To generate a valid web document (HTML, XML, WML, CSS etc) the Lua Script must follow the expected HTTP order to produce its output, first sending the correct headers and then sending the actual document contents.

CGILua offers some functions to ease these tasks, such as cgilua.htmlheader to produce the header for a HTML document and cgilua.put to send the document contents (or part of it).

For example, a HTML document which displays the sentence "Hello World!" can be generated with the following Lua Script:

cgilua.htmlheader()
cgilua.put([[
<html>
<head>
  <title>Hello World</title>
</head>
<body>
  <strong>Hello World!</strong>
</body>
</html>]])

It should be noted that the above example generates a "fixed" page: even though the page is generated at execution time there is no "variable" information. That means that the very same document could be generated directly with a simple static HTML file. However, Lua Scripts become especially useful when the document contains information which is not known beforehand or changes according to passed parameters, and it is necessary to generate a "dynamic" page.

Another easy example can be shown, this time using a Lua control structure, variables, and the concatenation operator:

cgilua.htmlheader()  

if cgi.language == 'english' then
  greeting = 'Hello World!'
elseif cgi.language == 'portuguese' then
  greeting = 'Olá Mundo!'
else
  greeting = '[unknown language]'
end

cgilua.put('<html>')  
cgilua.put('<head>')
cgilua.put('  <title>'..greeting..'</title>')
cgilua.put('</head>')
cgilua.put('<body>')
cgilua.put('  <strong>'..greeting..'</strong>')
cgilua.put('</body>')
cgilua.put('</html>')

In the above example the use of cgi.language indicates that language was passed to the Lua Script as a CGILua parameter, coming from a HTML form field (via POST) or from the URL used to activate it (via GET). CGILua automatically decodes such parameters so you can use them at will on your Lua Scripts and Lua Pages.

Lua Pages

A Lua Page is a text template file which will be processed by CGILua before the HTTP server sends it to the client. CGILua does not process the text itself but look for some special markups that include Lua code into the file. After all those markups are processed and merged with the template file, the results are sent to the client.

Lua Pages have a default .lp extension. They are a simpler way to make a dynamic page because there is no need to send the HTTP headers. Usually Lua Pages are HTML pages so CGILua sends the HTML header automatically.

Since there are some restrictions on the uses of HTTP headers sometimes a Lua Script will have to be used instead of a Lua Page.

The fundamental Lua Page markups are:

<?lua chunk ?>
Processes and merges the Lua chunk execution results where the markup is located in the template. The alternative form <% chunk %> can also be used.
<?lua= expression ?>
Processes and merges the Lua expression evaluation where the markup is located in the template. The alternative form <%= expression %> can also be used.

Note that the ending mark could not appear inside a Lua chunk or Lua expression even inside quotes. The Lua Pages pre-processor just makes global substitutions on the template, searching for a matching pair of markups and generating the corresponding Lua code to achieve the same result as the equivalent Lua Script.

The second example on the previous section could be written using a Lua Page like:

<html>
<?lua
if cgi.language == 'english' then
  greeting = 'Hello World!'
elseif cgi.language == 'portuguese' then
  greeting = 'Olá Mundo!'
else
  greeting = '[unknown language]'
end
?>
<head>
  <title><%= greeting %></title>
</head>
<body>
  <>strong<%= greeting %></strong>
</body>
</html>

HTML tags and Lua Page tags can be freely intermixed. However, as on other template languages, it's considered a best practice to not use explicit Lua logic on templates. The recommended aproach is to use only function calls that returns content chunks, so in this example, assuming that function getGreeting was definied somewhere else as

function getGreeting()
  local greeting
  if cgi.language == 'english' then
    greeting = 'Hello World!'
  elseif cgi.language == 'portuguese' then
    greeting = 'Olá Mundo!'
  else
    greeting = '[unknown language]'
  end
  return greeting
end

the Lua Page could be rewriten as:

<html>
<head>
  <title><%= getGreeting() %></title>
</head>
<body>
  <strong><%= getGreeting() %></strong>
</body>
</html>

Receiving parameters: the cgi table

CGILua offers an unified way of accessing data passed to the scripts for both HTTP method used (GET or POST). No matter which method was used on the client, all parameters will be provided inside the cgi table.

Usually all types of parameters will be available as strings. If the value of a parameter is a number, it will be converted to its string representation.

There are only two exceptions where the value will be a Lua table. The first case occurs on file uploads, where the corresponding table will have the following fields:

filename
the file name as given by the client.
filesize
the file size in bytes.
file
the temporary file handle. The file must be copied because CGILua will remove it after the script ends.

The other case that uses Lua tables occurs when there is more than one value associated with the same parameter name. This happens in the case of a selection list with multiple values; but it also occurs when the form (of the referrer) had two or more elements with the same name attribute (maybe because one was on a form and another was in the query string). All values will be inserted in an indexed table in the order in which they are handled.

Valid XHTML 1.0!

$Id: manual.html,v 1.8 2005/07/18 15:32:07 carregal Exp $