Databases

The function loadfile opens its first argument and tries to compile its contents as the body of a function of no arguments. If successful it returns the function, otherwise it returns nil followed by an error message. If no first argument is given it gets the chunk from the standard input. If it has a second argument "b" then the first argument has to be a compiled binary chunk; if "t" it has to be textual program code. If it has a third argument this is taken as an environment in which the compilation takes place.

The expression dofile (f) is equivalent to

 loadfile (f) ( ) 
If the contents of the file are needed more than once and in different contexts, it is more efficient to use loadfile once and to call its result multiple times.

Lua has a cunning trick up its sleeve when it comes to storing and retrieving data. Most databases require certain formats for writing data to storage, which need parsing when the data is read. Lua avoids this by using Lua syntax for the format, and dofile for reading the data.

   -- A small database for snods
   => X {
      { type = "odd", bludger = 57, } ;
      { type = "bland", } ;
      { bludger = 0, aspect = "frantic", } ;
      . . . .
      }
The database can be loaded with first giving X a value, a function on lists of tables, and then doing

 local db = dofile (dbasefile) 
Note that when a Lua function is applied to a single argument the parentheses can be omitted if the argument is a literal string, or, as in this case, a table constructor. So we can do different things by assigning different values to X before reading db . This technique is simply not available in BASIC.

If we take X to be the identity function

    X = \ (x) => x end 
then we just get db to be a list of tables. If we took

    X = \ (t)
       local count = 0
       for _, item in ipairs (t) do
           local _ENV = item
           if (type == "strange") and bludger then
               count + = bludger
           end -- if
       end -- for
       print ("total bludgery of strange snods = ", count)
     end -- function 
then db is nil but we get output for the total bludgery of the strange snods.