Lua scripts

Lua scripts are files with the extension .lua which are made up entirely of sentences in the Lua language. This kind of usage adopts a "traditional" form of programming, in which a script is strictly limited to being a program.

When a document is created using a Lua script, two basic concepts of CGI must be remembered:

  1. A script communicates with the server using the standard output (stdout), and any communication with the server must be sent by this channel.
  2. At the beginning of the script the type of document which is being sent must be identified.

In practice, the first item means that everything which is to be sent to the server must be sent using the Lua function write or print (see Lua Reference for more details). Note especially that HTML tags must be sent this way.

The second item means that the CGI script must generate an HTTP header line denoted "Content-type". For HTML documents this type corresponds exactly to the type "text/html". CGILua has a specific function for outputing HTML HTTP headers, called cgilua.htmlheader.

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

  
    cgilua.htmlheader()  
    write('<html>')  
    write('<head><title>Hello World</title></head>')  
    write('<body>')  
    write('<b>Hello World!</b>')  
    write('</body>')  
    write('</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. The very same document could be generated directly with HTML. However, Lua scripts become especially useful when the document contains information which is not known beforehand, 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()  
    write('<html>')  
      
    if cgi.language == 'english' then  
    	greeting = 'Hello World!'  
    elseif cgi.language == 'portuguese' then  
    	greeting = 'Olá Mundo!'  
    else  
    	greeting = '[unknown language']'  
    end  
    
    write('<head><title>'..greeting..'</title></head>')  
    write('<body>')  
    write('<b>'..greeting..'</b>')  
    write('</body>')  
    write('</html>')  

The use of cgi.language indicates that a variable named "language" was passed to the script as a parameter, coming from a form or from the URL used to activate it. CGILua automatically decodes such variables. For a more detailed description, see Forms and Building URLs later in this section. Complete examples of Lua scripts can be found in the section Examples.

HTML templates

An HTML template file (extension .html or .htm) is an ordinary HTML file which incorporates Lua codes and special markings. CGILua processes the incorporated instructions so that the HTML file expands with information obtained in real time. HTML template files are very expressive templates, thus being versatile and well adapted to the situation in which it is necessary to quickly generate codes and parameterize HTML pages.

An important feature of HTML pages is that there is a clear separation between static and dynamic information: static information is coded in HTML, and dynamic information is in Lua code. Since the Lua code and special markings are in comments in HTML or in phrases of free text, it is assured that the file as a whole is a valid HTML document.

Since the HTML template file is a valid HTML document, there are two important consequences:

These two facilities of CGILua lead to easier page maintenance and higher productivity, especially in large sites.

There are three types of special markings available for use in mixed HTML files:

Expression fields

FORMAT:
$| lua-expression |$

This leads to the insertion of the result of lua-expression in the HTML document. If the result of the expression is nil, nothing is inserted.

This type of CGILua marking is widely used where values should be accessed, such as those stored in variables or resulting from functions. For example, the following lines of mixed HTML use this type of marking:

  
    Good Morning, <b>$|firstname|$</b>  
    <input type="text" name="cor" value="$|cgi.cor|$">  
    <a href="$|cgilua.mkurl("ajuda.html", cgi )|$">Ajuda</a>  

In the first line, the content of the previously defined variable firstname is printed in bold.

In the second line, the value cgi.cor, which is passed as a parameter to the document, is used to initialize a text input field. If no value for cgi.cor is effectively passed as a parameter to the document, then the field is left blank.

In the third line a link is created to the document "ajuda.html", repassing all the values in the cgi table (see the CGILua function cgilua.mkurl).

Code fields

FORMAT:
<!--$$ lua-code $$-->

This leads to the interpretation of the lua-code contained between the marks <!--$$ and $$-->.

This type of marking places the Lua codes as HTML comments, allowing a large amount of Lua sentences to be introduced in a document without any possibility of interference with HTML syntax rules.

The use of a code field is recommended whenever the necessary processing is more elaborate than just printing Lua expressions, as is the case of defining Lua functions, reading a file, or consulting a database.

Parts of the code which is delimited by this marking may or may not produce visible effects in the HTML document. Typically, they are used to prepare information which will be exhibited with the Expression fields marking, but it is possible to force printing using the Lua function write. The two types of usage are compared in the examples below:

Example 1:
  
    <!--$$   
      function SubscriptionCharge()   
        dofile( 'charges.lua' )   
        return value_subscription   
      end   
    $$-->   
    
    <b><i>The value of the Subscription is: $|SubscriptionCharge()|$</i></b>   

Example 2:
  
    <!--$$   
      function SubscriptionCharge()   
        dofile( 'charges.lua' )   
        return value_subscription   
      end   
    
      write( '<b><i> The value of the Subscription is: ' )   
      write( SubscriptionCharge() )   
      write( '</i></b>' )   
    $$-->   

Loop directive

FORMAT:
<!--$$ LOOP start='cod_ini', test='cond_exec', action='cod_cycle' $$-->
[HTML code]
<!--$$ ENDLOOP $$-->

This type of marking repeats [lines-HTML] if and while cond_exec is true. Lua instructions can be executed before the start of the repetition and before the first test in cond_exec by using the control field start. The field action specifies Lua instructions which are to be executed at each cycle of the loop (cod_cycle).

The syntax of the control fields start, test, and action is similar to the construction for in C/C++. It is important to note that the other types of special markings (expression fields and code fields) can be used as normal markings in [lines-HTML]. LOOP markings can be nested as much as required.

The three examples below illustrate the use of this type of marking:

Example 1:
  
    Table of numbers 1 to 9:<br>   
    <table border=1>   
      <tr>   
    <!--$$ LOOP start='i=1', test='i<10', action='i=i+1' $$-->   
      <td>$|i|$</td>   
    <!--$$ ENDLOOP $$-->   
      </tr>   
    </table>  

Result of Example 1:
Table of numbers 1 to 9:
1 2 3 4 5 6 7 8 9

Example 2:
  
    <!--$$   
      data = {   
        { "Renata",  "20 years", "Brazilian" },   
        { "John",    "22 years ", "English" },   
        { "Natalie", "19 years ", "Spanish" },   
      }   
    $$-->   
    
    <b>Data in our records:</b><br><br>   
    <!--$$ LOOP start='i=1', teste='data[i]', action='i=i+1' $$-->   
      Nome:          $|dados[i][1]|$<br>   
      Age:           $|dados[i][2]|$<br>   
      Nationality:   $|dados[i][3]|$<br>   
      <br>   
    <!--$$ ENDLOOP $$-->   

Result of Example 2:
Data in our records:

Nome: Renata
Age: 20 years
Nationality: Brazilian

Nome: John
Age: 22 years
Nationality: English

Nome: Natalie
Age: 19 years
Nationality: Spanish

Example 3:

  
    Multiplication Table of numbers 1 to 10:<br><br>   
    <table border=1>   
      <tr>   
        <th>Number</th>   
        <!--$$ LOOP start='i=1', test='i<=10', action='i=i+1' $$-->   
        <th>x $|i|$</th>   
        <!--$$ ENDLOOP $$-->   
      </tr>   
      <!--$$ LOOP start='i=1', test='i<=10', action='i=i+1' $$-->   
      <tr>   
        <td><b>$|i|$</b></td>   
        <!--$$ LOOP start='j=1', test='j<=10', action='j=j+1' $$-->   
        <td align=right>$|i*j|$</td>   
        <!--$$ ENDLOOP $$-->   
      </tr>   
      <!--$$ ENDLOOP $$-->   
    </table>   

Result of Example 3:
Multiplication Table of numbers 1 to 10:

Number x 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100

If Directive

FORMAT:
<!--$$ IF test='cond_exec' $$-->
[HTML code (true condition)]
(<!--$$ ELSE $$-->
[HTML code (false condition)])
<!--$$ ENDIF $$-->

This type of marking includes (and processes) [HTML code (true condition)] if cond_exec is true. Otherwise, it includes the code [HTML code (false condition)].

The two examples below illustrate the use of this type of marking:

Example 1:

  
    <form ...>  
    User name:   
    <!--$$ IF test='cgi.editmode' $$-->   
      <input type="text" name="user" value="$|cgi.user|$">  
    <!--$$ ELSE $$-->   
      $|cgi.user|$  
    <!--$$ ENDIF $$-->   
    </form>  

Suppose cgi.editmode is set to some value, and cgi.user has value "John";
the result would be:

User name:

Example 2:

  
  <!--$$ IF test="cgi.draft" $$-->  
    This is a draft version of the manual.  
  <!--$$ ENDIF $$-->  

Suppose cgi.draft is set to some value;
the result would be:

This is a draft version of the manual.

Executing scripts

To execute a CGILua script, it is necessary to use special URLs. URLs of CGILua scripts (both Lua scripts and HTML templates) have the following format:

http:://<web-server>/<path-cgilua>/<path-script>

The URL of a CGILua script therefore encompasses two types of information:

  1. The virtual path (relative to the web server) in which CGILua is installed (<path-cgilua>).
  2. The path (relative to the home - or root - directory of the server) to the script to be executed (<path-script>).

Item 1 is defined when CGILua is installed. For example, it is common to install CGILua in a virtual directory (with permission for execution) called /scripts/. Since the executable program is named cgilua or cgilua.exe, depending on whether the version is for UNIX or Windows 95/NT (respectively), the <path-cgilua> component of the URL will be /scripts/cgilua or /scripts/cgilua.exe.

Item 2 is the same (virtual) path it would be if the file were a normal HTML file, without CGILua processing. Care should be taken if some mapping is defined in the configuration file of CGILua called map.lua, because the mapping will predominate over the default behavior.

CGILua provides a function specially designed to simplify the construction of URLs, cgilua.mkurl. This function must be called in all references to CGILua's scripts, allowing Web sites to be easily relocated from one server to another, or even from one directory structure to another. This function also provides great flexibility for defining script parameters, so its use is highly recommended. The most usual tags used to refer to scripts are <A HREF$gt, <FRAME$gt, and <FORM$gt, so their use with cgilua.mkurl in templates would be:


  
  <a href="$|mkurl('scriptA.html')|$">Link to Page A</a>  
    
  <frameset ...>  
  <frame src="$|mkurl('scriptB.html')|$">  
  </frameset>  
    
  <form method="POST" action="$|mkurl('scriptC.lua')|$">  
  ...  
  </form>  

Note that, unlike many other similar tools, a CGILua script is not executed as a direct map from the file itself to the interpreter (like .pl Perl files or .asp Microsoft Active Server Pages, for instance). From the server's point of view, always the same script is executed, the executable file cgilua. Then it is CGILua that uses the information provided by the PATH_INFO server variable to find and execute the user script. This scheme provides an enhanced flexibility for Web sites built with CGILua, allowing, for instance, several installations of the tool on the same server (with different configurations and permissions), easy migration of systems from one server to another (as no special permission is required for the user scripts), and the use of the standard HTML extension (.html) for CGILua HTML templates.


Information for users at PUC-Rio

CGILua is installed in several servers at PUC-Rio in multi-user configuration (various users share the same CGILua, only the scripts are in the user's account). As a reference, the configurations of the mostly used installations are provided below:


Lab-DI Configuration (UNIX server)
Value of<path-cgilua> /cgilua-cgi-bin/cgilua/
Format of<path-script> /~<username>/<script>
Real location of <path-script> ~<username>/public_html/<script>

Example:

URL => http://www.inf.puc-rio.br/cgilua-cgi-bin/cgilua/~anna/projetos/xpg.lua
Script physical path => ~anna/public_html/projetos/xpg.lua


Sala Cinza Configuration (UNIX server)
Value of<path-cgilua> /cgilua/cgilua/
Format of<path-script> /~<username>/<script>
Real location of <path-script> ~<username>/public_html/<script>

Example:

URL => http://www.ecp.inf.puc-rio.br/cgilua/cgilua/~inf1801/base/teste/index.html
Script physical path => /home/inf1901/public_html/base/teste/teste/index.html


Tecgraf - davis Configuration (NT server)
Value of<path-cgilua> /scripts/cgilua.exe/
Format of<path-script> /<script>
Real location of <path-script> \davisusersnonymouswww<script>

Example:

URL => http://davis.tecgraf.puc-rio.br/scripts/cgilua.exe/teste.lua
Script physical path => \davisusersnoymouswww este.lua


Forms

The trivial use of CGILua scripts is in processing data from HTML forms. CGILua facilitates this type of processing, automatically decoding the data received.

When a form is constructed in HTML, three components are important in processing the data:

For CGILua users, item 1 is straightforward: the methods POST and GET are both treated transparently by CGILua.

Item 2 requires more care. Both Lua script and HTML template files can be used for processing data from a form. However, one must be careful to set up the URL with the call to CGILua. It is recommended that the API function cgilua.mkurl be used for this.

Item 3 defines how (with what name) the values in the input fields of the data form are accessed in the processing script.

For example, consider the following form:
  
    <form method="POST" action="@|cgilua.mkurl( "receive.html" )|@">   
      <input type="text" name="firstname">   
      <input type="text" name="address">   
    
    <input type="submit" value="ok">   
    </form>  

POST is the method used; receive.html is the HTML template script which will process the data; firstname and address are the variables defined in the form (which holds the content of the fields).

A script which is executed to process data from the form can treat the information whatever way it is more convenient: write to a file, define a query to a database, display an HTML page, etc.

All the variables of a form can be accessed in the script which processes it through the Lua table cgi, in the form variable_name.

An implementation of the script receive.html referred to above could be:
  
  <html>   
  <head><title>Data Received</title></head>   
  <body>  
  <p>The form was filled in with   
  the following data: <p>Name: $|cgi.firstname|$   
  <p>Address: $|cgi.address|$   
  </body>  
  </html>  

In the section Examples there is a full example of how CGILua can be used to process data from a form. See the example "Simple Form".

File upload

CGILua supports "file upload", an HTML 3.2 mechanism for transferring files from the client to the server by means of HTML forms, available through HTML form fields with the "FILE" type (<input type="file"> tag). The names of the files to be transferred are defined interactively by the user. When the user submits the form, the files are saved to a directory in the server. CGILua supports the transfering of any kind of file (binary or text).

The HTML form used for uploading purpose has to conform to some specific rules. The following attributes of the <FORM> HTML tag must be specified: method="POST" and enctype="multipart/form-data".

Mechanisms were implemented allowing the developer to specify the name with which and the directory in which the file will be saved in the server. The specification mechanism is very flexible, allowing the developer to define any naming rule for the files that will be sent to the server. Basically, this mechanism consists in defining rules using Lua regular expressions. These rules must be stored into a Lua table called cgilua.uploadrules (file cgilua.conf/map.lua), which is exemplified below:

  
  cgilua.uploadrules = {  
    { pattern="(.*)%.doc", target="upload%.%1%.doc"},  
    { pattern="(.*)%.bmp", target="upload%.%1%.bmp"},  
    ; root_dir = "c:/temp/"  
  }  

These rules specify that all files with be saved in the c:/temp/ directory, but the files with extension .doc and .bmp will have a "upload" prefix appended.

The cgilua.uploadrules table is the table used by default to define the naming and the transfer rules for the files. It is also possible to specify alternative rules tables, when is needed that a script use different rules than the default ones. Any rules table must necessarily contain the field root_dir, which defines the directory in which the files must be stored in the server. Apart from the root_dir field, the rules can be freely specified. Any number of rules can be specified, and there are tested until there is a match. Each rule must follow the format { pattern=pattern, target=target }, with an optional field func, as described above:

Alternative rules tables

It is possible to specify alternative rule tables to be used in a given HTML form.

For such, for each "FILE" field there must be a "HIDDEN" field immediately before it containing as value (value attribute) the name of the Lua global variable that contains the rule table to be used for the associated "FILE" field. The name of the "HIDDEN" field (name attribute) needs to have the following format: the prefix must be the string 'rules_', and the suffix must be the same name used in the name attribute of the "FILE" field associated to it. It is worth noting that using the "HIDDEN" field to provide help in the upload process is not required. In case it is not specified by the developer, the default rule table (defined in the file cgilua.conf/map.lua) will be used.

In the examplary form below, the Lua table upload_example2 could be used to establish upload rules:
  
  <form method="POST" action="$|cgilua.mkurl( 'etc.lua' )|$" enctype="multipart/form-data">  
    <input type="hidden" name="rules_upload_example2">  
    File name: <input type="file" name="upload_example2">  
    <input type="submit">  
  </form>  

Transfer log

The script makes a table called cgilua.upload_transferlog available with a log of the transferences performed by the script to a given form. This log contains the original file name, the name with which the file was saved in the server, and the directory in which it was saved. There is also a predefined function that prints the values in the cgilua.upload_transferlog table in a fixed format:

For examples of scripts that use file uploads, see section Examples.

Examples

Environment variables

Scripts needed:

The correct functioning of the script can be checked by the link: env

Sending mail

Scripts needed:

The correct functioning of the script can be checked by the link: mail

Form

Scripts needed:

The correct functioning of the script can be checked by the link: form

Upload

Scripts needed:




Last update in 28/05/1999