Gravwars AI Programming Reference Manual and Reference Manual of the Programming Language Lua 4.0


1 - Introduction

Lua is an extension programming language designed to support general procedural programming with data description facilities. It has been incorperated into Gravwars to allow for the design of AIs and to allow for a level of protection of the program from user built AIs. It also forces the AIs to get the same scanner data a human player would. This document borrows heavily from the origional Lua referance manual while focusing on only those aspects that are of importance to writing an AI for Gravwars. If you would like to use Lua in a program you are writing see this link:

       http://www.tecgraf.puc-rio.br/lua/


2 - Environment and Chunks

All statements in Lua are executed in a global environment. Global variables in Lua do not need to be declared. Any variable is assumed to be global unless explicitly declared local (see Section 4.4.6). Before the first assignment, the value of a global variable is nil

The unit of execution of Lua is called a chunk. A chunk is simply a sequence of statements, which are executed sequentially. Each statement can be optionally followed by a semicolon:

       chunk ::= {stat [`;']}
Statements are described in Section 4.4. (The notation above is the usual extended BNF, in which {a} means 0 or more a's, [a] means an optional a, and (a)+ means one or more a's. The complete syntax of Lua is given in BNF).


3 - Types and Tags

Lua is a dynamically typed language. This means that variables do not have types; only values do. Therefore, there are no type definitions in the language. All values carry their own type. Besides a type, all values also have a tag.

There are six basic types in Lua: nil, number, string, function, userdata, and table. Nil is the type of the value nil, whose main property is to be different from any other value. Number represents real (double-precision floating-point) numbers, while string has the usual meaning. Lua is 8-bit clean, and so strings may contain any 8-bit character, including embedded zeros ('\0') (see Section 4.1). The type function returns a string describing the type of a given value (see Section 6.1).

Functions are considered first-class values in Lua. This means that functions can be stored in variables, passed as arguments to other functions, and returned as results.

The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil). Therefore, this type may be used not only to represent ordinary arrays, but also symbol tables, sets, records, graphs, trees, etc. Tables are the main data structuring mechanism in Lua. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. Tables may also carry methods: Because functions are first class values, table fields may contain functions. The form t:f(x) is syntactic sugar for t.f(t,x), which calls the method f from the table t passing the table itself as the first parameter (see Section 4.5.9).

Note that tables are objects, and not values. Variables do not contain tables, only references to them. Assignment, parameter passing, and returns always manipulate references to tables, and do not imply any kind of copy. Moreover, tables must be explicitly created before used (see Section 4.5.7).


4 - The Language

This section describes the lexis, the syntax, and the semantics of Lua.

4.1 - Lexical Conventions

Identifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit. This coincides with the definition of identifiers in most languages, except that the definition of letter depends on the current locale: Any character considered alphabetic by the current locale can be used in an identifier. The following words are reserved, and cannot be used as identifiers:

       and       break     do        else      elseif
       end       for       function  if        in
       local     nil       not       or        repeat
       return    then      until     while

Lua is a case-sensitive language: and is a reserved word, but And and ánd (if the locale permits) are two different, valid identifiers. As a convention, identifiers starting with underscore followed by uppercase letters (such as _INPUT) are reserved for internal variables.

The following strings denote other tokens:

       ~=    <=    >=    <     >     ==    =     +     -     *     /
       (     )     {     }     [     ]     ;     ,     .     ..    ...

Literal strings can be delimited by matching single or double quotes, and can contain the C-like escape sequences `\a' (bell), `\b' (backspace), `\f' (form feed), `\n' (newline), `\r' (carriage return), `\t' (horizontal tab), `\v' (vertical tab), `\\' (backslash), `\"' (double quote), `\'' (single quote), and `\newline' (that is, a backslash followed by a real newline, which results in a newline in the string). A character in a string may also be specified by its numerical value, through the escape sequence `\ddd', where ddd is a sequence of up to three decimal digits. Strings in Lua may contain any 8-bit value, including embedded zeros, which can be specified as `\000'.

Literal strings can also be delimited by matching [[ ... ]]. Literals in this bracketed form may run for several lines, may contain nested [[ ... ]] pairs, and do not interpret escape sequences. This form is specially convenient for writing strings that contain program pieces or other quoted strings. As an example, in a system using ASCII, the following three literals are equivalent:

       1)   "alo\n123\""
       2)   '\97lo\10\04923"'
       3)   [[alo
            123"]]

Comments start anywhere outside a string with a double hyphen (--) and run until the end of the line. Moreover, the first line of a chunk is skipped if it starts with #. This facility allows the use of Lua as a script interpreter in Unix systems (see Section 8).

Numerical constants may be written with an optional decimal part and an optional decimal exponent. Examples of valid numerical constants are

       3     3.0     3.1416  314.16e-2   0.31416E1

4.2 - Coercion

Lua provides some automatic conversions between values at run time. Any arithmetic operation applied to a string tries to convert that string to a number, following the usual rules. Conversely, whenever a number is used when a string is expected, that number is converted to a string, in a reasonable format. The format is chosen so that a conversion from number to string then back to number reproduces the original number exactly. Thus, the conversion does not necessarily produces nice-looking text for some numbers. For complete control of how numbers are converted to strings, use the format function (see Section 6.2).

4.3 - Adjustment

Functions in Lua can return many values. Because there are no type declarations, when a function is called the system does not know how many values the function will return, or how many parameters it needs. Therefore, sometimes, a list of values must be adjusted, at run time, to a given length. If there are more values than are needed, then the excess values are thrown away. If there are less values than are needed, then the list is extended with as many nil's as needed. This adjustment occurs in multiple assignments (see Section 4.4.2) and in function calls (see Section 4.5.8).

4.4 - Statements

Lua supports an almost conventional set of statements, similar to those in Pascal or C. The conventional commands include assignment, control structures, and procedure calls. Non-conventional commands include table constructors (see Section 4.5.7) and local variable declarations (see Section 4.4.6).

4.4.1 - Blocks

A block is a list of statements; syntactically, a block is equal to a chunk:
       block ::= chunk

A block may be explicitly delimited:

       stat ::= do block end
Explicit blocks are useful to control the scope of local variables (see Section 4.4.6). Explicit blocks are also sometimes used to add a return or break statement in the middle of another block (see Section 4.4.3).

4.4.2 - Assignment

Lua allows multiple assignment. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas:
       stat ::= varlist1 `=' explist1
       varlist1 ::= var {`,' var}
This statement first evaluates all values on the right side and eventual indices on the left side, and then makes the assignments. So, the code
       i = 3
       i, a[i] = 4, 20
sets a[3] to 20, but does not affect a[4] because the i in a[i] is evaluated before it is assigned 4.

Multiple assignment can be used to exchange two values, as in

       x, y = y, x

The two lists in a multiple assignment may have different lengths. Before the assignment, the list of values is adjusted to the length of the list of variables (see Section 4.3).

A single name can denote a global variable, a local variable, or a formal parameter:

       var ::= name

Square brackets are used to index a table:

       var ::= varorfunc `[' exp1 `]'
       varorfunc ::= var | functioncall
The varorfunc should result in a table value, from where the field indexed by the expression exp1 value gets the assigned value.

The syntax var.NAME is just syntactic sugar for var["NAME"]:

       var ::= varorfunc `.' name

The meaning of assignments and evaluations of global variables and indexed variables can be changed by tag methods (see Section 4.8). Actually, an assignment x = val, where x is a global variable, is equivalent to a call setglobal("x", val) and an assignment t[i] = val is equivalent to settable_event(t,i,val). See Section 4.8 for a complete description of these functions (setglobal is in the basic library; settable_event is used for explanatory purposes only).

4.4.3 - Control Structures

The control structures if, while, and repeat have the usual meaning and familiar syntax
       stat ::= while exp1 do block end
       stat ::= repeat block until exp1
       stat ::= if exp1 then block {elseif exp1 then block} [else block] end
The condition expression exp1 of a control structure may return any value. All values different from nil are considered true; only nil is considered false.

The return statement is used to return values from a function or from a chunk. Because functions or chunks may return more than one value, the syntax for the return statement is

       stat ::= return [explist1]

The break statement can be used to terminate the execution of a loop, skipping to the next statement after the loop:

       stat ::= break
A break ends the innermost enclosing loop (while, repeat, or for).

For syntactic reasons, return and break statements can only be written as the last statements of a block. If it is really necessary to return or break in the middle of a block, an explicit inner block can used, as in the idiom `do return end', because now return is last statement in the inner block.

4.4.4 - For Statement

The for statement has two forms, one for numbers and one for tables. The numerical for loop has the following syntax:

       stat ::= for name `=' exp1 `,' exp1 [`,' exp1] do block end
A for statement like
       for var = e1 ,e2, e3 do block end
is equivalent to the code:
       do
         local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
         if not (var and _limit and _step) then error() end
         while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
           block
           var = var+_step
         end
       end
Note the following:

The table for statement traverses all pairs (index,value) of a given table. It has the following syntax:

       stat ::= for name `,' name in exp1 do block end
A for statement like
       for index, value in exp do block end
is equivalent to the code:
       do
         local _t = exp
         local index, value = next(t, nil)
         while index do
           block
           index, value = next(t, index)
         end
       end
Note the following:

4.4.5 - Function Calls as Statements

Because of possible side-effects, function calls can be executed as statements:
       stat ::= functioncall
In this case, all returned values are thrown away. Function calls are explained in Section 4.5.8.

4.4.6 - Local Declarations

Local variables may be declared anywhere inside a block. The declaration may include an initial assignment:
       stat ::= local declist [init]
       declist ::= name {`,' name}
       init ::= `=' explist1
If present, an initial assignment has the same semantics of a multiple assignment. Otherwise, all variables are initialized with nil.

A chunk is also a block, and so local variables can be declared outside any explicit block.

The scope of local variables begins after the declaration and lasts until the end of the block. Thus, the code local print=print creates a local variable called print whose initial value is that of the global variable of the same name.

4.5 - Expressions

4.5.1 - Basic Expressions

The basic expressions in Lua are
       exp ::= `(' exp `)'
       exp ::= nil
       exp ::= number
       exp ::= literal
       exp ::= var
       exp ::= upvalue
       exp ::= function
       exp ::= functioncall
       exp ::= tableconstructor

Numbers (numerical constants) and literal strings are explained in Section 4.1; variables are explained in Section 4.4.2; upvalues are explained in Section 4.6; function definitions are explained in Section 4.5.9; function calls are explained in Section 4.5.8. Table constructors are explained in Section 4.5.7.

An access to a global variable x is equivalent to a call getglobal("x") and an access to an indexed variable t[i] is equivalent to a call gettable_event(t,i). See Section 4.8 for a description of these functions (getglobal is in the basic library; gettable_event is used for explanatory purposes only).

The non-terminal exp1 is used to indicate that the values returned by an expression must be adjusted to one single value:

       exp1 ::= exp

4.5.2 - Arithmetic Operators

Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation); and unary - (negation). If the operands are numbers, or strings that can be converted to numbers (according to the rules given in Section 4.2), then all operations except exponentiation have the usual meaning. Otherwise, an appropriate tag method is called (see Section 4.8). An exponentiation always calls a tag method. The standard mathematical library redefines this method for numbers, giving the expected meaning to exponentiation (see Section 6.3).

4.5.3 - Relational Operators

The relational operators in Lua are
       ==    ~=    <     >     <=    >=
These operators return nil as false and a value different from nil as true.

Equality (==) first compares the tags of its operands. If they are different, then the result is nil. Otherwise, their values are compared. Numbers and strings are compared in the usual way. Tables, userdata, and functions are compared by reference, that is, two tables are considered equal only if they are the same table. The operator ~= is exactly the negation of equality (==).

The conversion rules of Section 4.2 do not apply to equality comparisons. Thus, "0"==0 evaluates to false, and t[0] and t["0"] denote different entries in a table.

The order operators work as follows. If both arguments are numbers, then they are compared as such. Otherwise, if both arguments are strings, then their values are compared using lexicographical order. Otherwise, the ``lt'' tag method is called (see Section 4.8).

4.5.4 - Logical Operators

The logical operators in Lua are
       and   or    not
Like the control structures, all logical operators consider nil as false and anything else as true.

The conjunction operator and returns nil if its first argument is nil; otherwise, it returns its second argument. The disjunction operator or returns its first argument if it is different from nil; otherwise, it returns its second argument. Both and and or use short-cut evaluation, that is, the second operand is evaluated only if necessary.

There are two useful Lua idioms that use logical operators. The first idiom is

       x = x or v
which is equivalent to
       if x == nil then x = v end
This idiom sets x to a default value v when x is not set.

The second idiom is

       x = a and b or c
which should be read as x = (a and b) or c. This idiom is equivalent to
       if a then x = b else x = c end
provided that b is not nil.

4.5.5 - Concatenation

The string concatenation operator in Lua is denoted by two dots (`..'). If both operands are strings or numbers, then they are converted to strings according to the rules in Section 4.2. Otherwise, the ``concat'' tag method is called (see Section 4.8).

4.5.6 - Precedence

Operator precedence in Lua follows the table below, from the lower to the higher priority:
       and   or
       <     >     <=    >=    ~=    ==
       ..
       +     -
       *     /
       not   - (unary)
       ^
All binary operators are left associative, except for ^ (exponentiation), which is right associative. The pre-compiler may rearrange the order of evaluation of associative operators (such as .. or +), as long as these optimizations do not change normal results. However, these optimizations may change some results if you define non-associative tag methods for these operators.

4.5.7 - Table Constructors

Table constructors are expressions that create tables; every time a constructor is evaluated, a new table is created. Constructors can be used to create empty tables, or to create a table and initialize some of its fields. The general syntax for constructors is
       tableconstructor ::= `{' fieldlist `}'
       fieldlist ::= lfieldlist | ffieldlist | lfieldlist `;' ffieldlist | ffieldlist `;' lfieldlist
       lfieldlist ::= [lfieldlist1]
       ffieldlist ::= [ffieldlist1]

The form lfieldlist1 is used to initialize lists:

       lfieldlist1 ::= exp {`,' exp} [`,']
The expressions in the list are assigned to consecutive numerical indices, starting with 1. For example,
       a = {"v1", "v2", 34}
is equivalent to
       do
         local temp = {}
         temp[1] = "v1"
         temp[2] = "v2"
         temp[3] = 34
         a = temp
       end

The form ffieldlist1 initializes other fields in a table:

       ffieldlist1 ::= ffield {`,' ffield} [`,']
       ffield ::= `[' exp `]' `=' exp | name `=' exp
For example,
       a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
is equivalent to
       do
         local temp = {}
         temp[f(k)] = g(y)
         temp.x = 1    -- or temp["x"] = 1
         temp.y = 3    -- or temp["y"] = 3
         temp[0] = b+c
         a = temp
       end
An expression like {x = 1, y = 4} is in fact syntactic sugar for {["x"] = 1, ["y"] = 4}.

Both forms may have an optional trailing comma, and can be used in the same constructor separated by a semi-colon. For example, all forms below are correct.

       x = {;}
       x = {"a", "b",}
       x = {type="list"; "a", "b"}
       x = {f(0), f(1), f(2),; n=3,}

4.5.8 - Function Calls

A function call in Lua has the following syntax:
       functioncall ::= varorfunc args
First, varorfunc is evaluated. If its value has type function, then this function is called, with the given arguments. Otherwise, the ``function'' tag method is called, having as first parameter the value of varorfunc, and then the original call arguments (see Section 4.8).

The form

       functioncall ::= varorfunc `:' name args
can be used to call ``methods''. A call v:name(...) is syntactic sugar for v.name(v, ...), except that v is evaluated only once.

Arguments have the following syntax:

       args ::= `(' [explist1] `)'
       args ::= tableconstructor
       args ::= literal
       explist1 ::= {exp1 `,'} exp
All argument expressions are evaluated before the call. A call of the form f{...} is syntactic sugar for f({...}), that is, the argument list is a single new table. A call of the form f'...' (or f"..." or f[[...]]) is syntactic sugar for f('...'), that is, the argument list is a single literal string.

Because a function can return any number of results (see Section 4.4.3), the number of results must be adjusted before they are used (see Section 4.3). If the function is called as a statement (see Section 4.4.5), then its return list is adjusted to 0, thus discarding all returned values. If the function is called in a place that needs a single value (syntactically denoted by the non-terminal exp1), then its return list is adjusted to 1, thus discarding all returned values but the first one. If the function is called in a place that can hold many values (syntactically denoted by the non-terminal exp), then no adjustment is made. The only places that can hold many values is the last (or the only) expression in an assignment, in an argument list, or in the return statement. Here are some examples:

       f()                -- adjusted to 0 results
       g(f(), x)          -- f() is adjusted to 1 result
       g(x, f())          -- g gets x plus all values returned by f()
       a,b,c = f(), x     -- f() is adjusted to 1 result (and c gets nil)
       a,b,c = x, f()     -- f() is adjusted to 2
       a,b,c = f()        -- f() is adjusted to 3
       return f()         -- returns all values returned by f()
       return x,y,f()     -- returns a, b, and all values returned by f()

4.5.9 - Function Definitions

The syntax for function definition is

       function ::= function `(' [parlist1] `)' block end
       stat ::= function funcname `(' [parlist1] `)' block end
       funcname ::= name | name `.' name | name `:' name
The statement
       function f () ... end
is just syntactic sugar for
       f = function () ... end
and the statement
       function v.f () ... end
is syntactic sugar for
       v.f = function () ... end

A function definition is an executable expression, whose value has type function. When Lua pre-compiles a chunk, all its function bodies are pre-compiled too. Then, whenever Lua executes the function definition, its upvalues are fixed (see Section 4.6), and the function is instantiated (or closed). This function instance (or closure) is the final value of the expression. Different instances of the same function may have different upvalues.

Parameters act as local variables, initialized with the argument values:

       parlist1 ::= `...'
       parlist1 ::= name {`,' name} [`,' `...']
When a function is called, the list of arguments is adjusted to the length of the list of parameters (see Section 4.3), unless the function is a vararg function, which is indicated by three dots (`...') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments into an implicit parameter, called arg. The value of arg is a table, with a field n whose value is the number of extra arguments, and the extra arguments at positions 1, 2, ..., n.

As an example, consider the following definitions:

       function f(a, b) end
       function g(a, b, ...) end
       function r() return 1,2,3 end
Then, we have the following mapping from arguments to parameters:
       CALL            PARAMETERS

f(3) a=3, b=nil f(3, 4) a=3, b=4 f(3, 4, 5) a=3, b=4 f(r(), 10) a=1, b=10 f(r()) a=1, b=2

g(3) a=3, b=nil, arg={n=0} g(3, 4) a=3, b=4, arg={n=0} g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} g(5, r()) a=5, b=1, arg={2, 3; n=2}

Results are returned using the return statement (see Section 4.4.3). If control reaches the end of a function without encountering a return statement, then the function returns with no results.

The syntax

       funcname ::= name `:' name
is used for defining methods, that is, functions that have an implicit extra parameter self.

The statement

       function v:f (...) ... end
is just syntactic sugar for
       v.f = function (self, ...) ... end
Note that the function gets an extra formal parameter called self.

4.6 - Visibility and Upvalues

A function body may refer to its own local variables (which include its parameters) and to global variables, as long as they are not shadowed by local variables with the same name from enclosing functions. A function cannot access a local variable from an enclosing function, since such variables may no longer exist when the function is called. However, a function may access the value of a local variable from an enclosing function, using upvalues, whose syntax is

       upvalue ::= `%' name

An upvalue is somewhat similar to a variable expression, but whose value is frozen when the function wherein it appears is instantiated. The name used in an upvalue may be the name of any variable visible at the point where the function is defined, that is, global variables and local variables from the immediately enclosing function. Note that when the upvalue is a table, only the reference to that table (which is the value of the upvalue) is frozen; the table contents can be changed at will. Using table values as upvalues is a technique for having writable but private state attached to functions.

Here are some examples:

       a,b,c = 1,2,3   -- global variables
       local d
       function f (x)
         local b = {}  -- x and b are local to f; b shadows the global b
         local g = function (a)
           local y     -- a and y are local to g
           p = a       -- OK, access local `a'
           p = c       -- OK, access global `c'
           p = b       -- ERROR: cannot access a variable in outer scope
           p = %b      -- OK, access frozen value of `b' (local to `f')
           %b = 3      -- ERROR: cannot change an upvalue
           %b.x = 3    -- OK, change the table contents
           p = %c      -- OK, access frozen value of global `c'
           p = %y      -- ERROR: `y' is not visible where `g' is defined
           p = %d      -- ERROR: `d' is not visible where `g' is defined
         end           -- g
       end             -- f

4.7 - Error Handling

Because Lua is an extension language, all Lua actions start from C code in the host program calling a function from the Lua library. Whenever an error occurs during Lua compilation or execution, the function _ERRORMESSAGE is called (provided it is different from nil), and then the corresponding function from the library (lua_dofile, lua_dostring, lua_dobuffer, or lua_call) is terminated, returning an error condition.

Memory allocation errors are an exception to the previous rule. When memory allocation fails, Lua may not be able to execute the _ERRORMESSAGE function. So, for this kind of error, Lua does not call the _ERRORMESSAGE function; instead, the corresponding function from the library returns immediately with a special error code (LUA_ERRMEM). This and other error codes are defined in lua.h; Section 5.8.

The only argument to _ERRORMESSAGE is a string describing the error. The default definition for this function calls _ALERT, which prints the message to stderr (see Section 6.1). The standard I/O library redefines _ERRORMESSAGE and uses the debug facilities (see Section 7) to print some extra information, such as a call stack traceback.

Lua code can explicitly generate an error by calling the function error (see Section 6.1). Lua code can ``catch'' an error using the function call (see Section 6.1).


Functions in gwar luai

Basic Functions

The basic library provides some core functions to Lua.

assert (v [, message])

Issues an ``assertion failed!'' error when its argument v is nil. This function is equivalent to the following Lua function:
       function assert (v, m)
         if not v then
           m = m or ""
           error("assertion failed!  " .. m)
         end
       end

call (func, arg [, mode [, errhandler]])

Calls function func with the arguments given by the table arg. The call is equivalent to
       func(arg[1], arg[2], ..., arg[n])
where n is the result of getn(arg) (see Section 6.1). All results from func are simply returned by call.

By default, if an error occurs during the call to func, the error is propagated. If the string mode contains "x", then the call is protected. In this mode, function call does not propagate an error, regardless of what happens during the call. Instead, it returns nil to signal the error (besides calling the appropriated error handler).

dofile (filename)

Receives a file name, opens the named file, and executes its contents as a Lua chunk, or as pre-compiled chunks. When called without arguments, dofile executes the contents of the standard input (stdin). If there is any error executing the file, then dofile returns nil. Otherwise, it returns the values returned by the chunk, or a non-nil value if the chunk returns no values. It issues an error when called with a non-string argument.

dostring (string [, chunkname])

Executes a given string as a Lua chunk. If there is any error executing the string, then dostring returns nil. Otherwise, it returns the values returned by the chunk, or a non-nil value if the chunk returns no values. The optional parameter chunkname is the ``name of the chunk'', used in error messages and debug information.

error (message)

Calls the error handler (see Section 4.7) and then terminates the last protected function called (in C: lua_dofile, lua_dostring, lua_dobuffer, or lua_callfunction; in Lua: dofile, dostring, or call in protected mode). If message is nil, then the error handler is not called. Function error never returns.

foreach (table, func)

Executes the given func over all elements of table. For each element, the function is called with the index and respective value as arguments. If the function returns any non-nil value, then the loop is broken, and this value is returned as the final value of foreach. This function could be defined in Lua:
       function foreach (t, f)
         for i, v in t do
           local res = f(i, v)
           if res then return res end
         end
       end

The behavior of foreach is undefined if you change the table t during the traversal.

foreachi (table, func)

Executes the given func over the numerical indices of table. For each index, the function is called with the index and respective value as arguments. Indices are visited in sequential order, from 1 to n, where n is the result of getn(table) (see Section 6.1). If the function returns any non-nil value, then the loop is broken, and this value is returned as the final value of foreachi. This function could be defined in Lua:
       function foreachi (t, f)
         for i=1,getn(t) do
           local res = f(i, t[i])
           if res then return res end
         end
       end

getglobal (name)

Gets the value of a global variable, or calls a tag method for ``getglobal''. Its full semantics is explained in Section 4.8. The string name does not need to be a syntactically valid variable name.

getn (table)

Returns the ``size'' of a table, when seen as a list. If the table has an n field with a numeric value, this value is the ``size'' of the table. Otherwise, the ``size'' is the largest numerical index with a non-nil value in the table. This function could be defined in Lua:
       function getn (t)
         if type(t.n) == "number" then return t.n end
         local max = 0
         for i, _ in t do
           if type(i) == "number" and i>max then max=i end
         end
         return max
       end

globals ([table])

Returns the current table of globals. If the argument table is given, then it also sets this table as the table of globals.

newtag ()

Returns a new tag.

next (table, [index])

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and the value associated with the index. When called with nil as its second argument, next returns the first index of the table and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil.

Lua has no declaration of fields; semantically, there is no difference between a field not present in a table or a field with value nil. Therefore, next only considers fields with non-nil values. The order in which the indices are enumerated is not specified, even for numeric indices (to traverse a table in numeric order, use a numerical for or the function foreachi).

The behavior of next is undefined if you change the table during the traversal.

print (e1, e2, ...)

Receives any number of arguments, and prints their values using the strings returned by tostring. This function is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. See Section 6.4 for functions for formatted output.

sort (table [, comp])

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the result of getn(table) (see Section 6.1). If comp is given, then it must be a function that receives two table elements, and returns true (that is, a value different from nil) when the first is less than the second (so that not comp(a[i+1], a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

The sort algorithm is not stable (that is, elements considered equal by the given order may have their relative positions changed by the sort).

tinsert (table [, pos] , value)

Inserts element value at table position pos, shifting other elements to open space, if necessary. The default value for pos is n+1, where n is the result of getn(table) (see Section 6.1), so that a call tinsert(t,x) inserts x at the end of table t. This function also sets or increments the field n of the table to n+1. This function is equivalent to the following Lua function, except that the table accesses are all raw (that is, without tag methods):

       function tinsert (t, ...)
         local pos, value
         local n = getn(t)
         if arg.n == 1 then
           pos, value = n+1, arg[1]
         else
           pos, value = arg[1], arg[2]
         end
         t.n = n+1;
         for i=n,pos,-1 do
           t[i+1] = t[i]
         end
         t[pos] = value
       end

tremove (table [, pos])

Removes from table the element at position pos, shifting other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the result of getn(table) (see Section 6.1), so that a call tremove(t) removes the last element of table t. This function also sets or decrements the field n of the table to n-1.

This function is equivalent to the following Lua function, except that the table accesses are all raw (that is, without tag methods):

       function tremove (t, pos)
         local n = getn(t)
         if n<=0 then return end
         pos = pos or n
         local value = t[pos]
         for i=pos,n-1 do
           t[i] = t[i+1]
         end
         t[n] = nil
         t.n = n-1
         return value
       end

type (v)

Allows Lua programs to test the type of a value. It receives one argument, and returns its type, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "table", "function", and "userdata".

Mathematical Functions

This library is an interface to some functions of the standard C math library. In addition, it registers a tag method for the binary operator ^ that returns x^y when applied to numbers x^y.

The library provides the following functions:

       abs  acos  asin  atan  atan2  ceil  cos  deg    exp    floor   log  log10
       max  min   mod   rad   sin    sqrt  tan  frexp  ldexp  random  randomseed
plus a global variable PI. Most of them are only interfaces to the homonymous functions in the C library, except that, for the trigonometric functions, all angles are expressed in degrees, not radians. The functions deg and rad can be used to convert between radians and degrees.

The function max returns the maximum value of its numeric arguments. Similarly, min computes the minimum. Both can be used with 1, 2, or more arguments.

The functions random and randomseed are interfaces to the simple random generator functions rand and srand, provided by ANSI C. (No guarantees can be given for their statistical properties.) The function random, when called without arguments, returns a pseudo-random real number in the range [0,1). When called with a number n, random returns a pseudo-random integer in the range [1,n]. When called with two arguments, l and u, random returns a pseudo-random integer in the range [l,u].

Gravwars Interface Functions

This library is the set of functions that allow the AI to interact with the game.

nxfoe ([s_idx])

Returns the next index of an enemy ship/mecha in scanner range or 0 for end of list. s_idx if listed means starting index. Otherwise the last thing scanned is used as the starting index.

nxfriend ([s_idx])

Functions the same as nxfoe but returns friendly ships/mecha.

nxobj ([s_idx [, otype]])

Returns the next index of an object in scanner range. If otype is used only objects of that type are listed.

canisee ([s_idx])

Returns true if s_idx is being detected by the scanner.

isalive ([s_idx])

Returns true if s_idx is alive.

locate ([s_idx])

Returns the x,y coordinants of s_idx or nil,nil if out of scanner range.

moving ([s_idx])

Returns the vx,vy in pps of s_idx or nil,nil if out of scanner range.

hpscan ([s_idx])

Returns the hp,mhp of s_idx or nil,nil if scanner cannot detect its hit points.

shieldscan ([s_idx])

Returns the shield charge of s_idx or nil if scanner cannot detect its shield charge.

energyscan ([s_idx])

Returns the energy,maxenergy of s_idx or nil,nil if scanner cannot detect its energy.

crewscan ([s_idx])

Returns the crew,maxcrew of s_idx or nil,nil if scanner cannot detect its crew.

setgo (x, y [, velocity])

Ship flys to point x,y at velocity in range of 0.0 to 1.0. velocity = 1.0 is assumed if not explicitly set. Overrides a call to turn.

nummounts ()

Returns number of mounts.

sysinfo (midx)

Returns name,otype,subtype of midx.

fire (midx, angle [, power [, spread ]])

Trys to fire weapon on midx at angle. power and spread have different meanings depending on what's being fired.

numweapon ()

returns the number of weapons on the ship

weapon (w_idx)

returns the system index of your w_idx'th weapon

setautofire (midx [, on])

puts a weapon into auto fire mode. at the last thing fired at. if on == 0 autofire is set to off.

load (midx)

Returns load, maxload or rounds, max rounds for weapon midx.

isloaded (midx)

returns true on weapon armed, 0 on reloading.

dist (x1, y1 [, x2, y2])

Calculates the distance between 2 points or 1 point and 0,0.

nameof (s_idx)

returns the name of s_idx.

range ([s_idx1 [, s_idx2]])

Returns range between 2 objects (from the radius). Retuns the range between s_idx1 and me or me and the last scanned ship (if no arguments).

setpower (midx)

Sets power to system midx. Returns 0 on failure.

thrust (velocity [, straff_vel])

Fires engines at velocity in range of -1.0(max backwards) to 1.0(max ahead). Fires straffing engines at straff_vel -1.0(max left) to 1.0(max right).

turn ([angle])

Ship turns until it reachesangle. If no angle set cancles all movement. Overrides a setgo.

invoke (midx)

Invokes a mounts special ability. Returns 0 on failure.

Gravwars Flow Control Functions

This library is the set of functions that allows the AI to recieve signals from the game. It also emulates some os like functions.

bigloop ([n])

Insert this instruction in your code to pause durring your main loop to make the ai wait until the next game cycle when this is called twice in one cycle. This keeps gwarserver running fast. if n isn't explicitly set n = 1. if you have several main loops use a different n for each.

catch (signum)

makes the AI able to reciece signum signals. Ex: SIGFIRE, SIGCOLLIDE.

uncatch (signum)

makes the AI ignore signum

sig ()

Returns True on waiting signals

sigwait ()

AI blocks until a signal happens.

sigtake (s1 [, s2, ...])

Returns true if any of the signals occured and unsets the signal flag for each.

say (s1 [, s2, ...])

writes debug string info to the default location.

trace (set)

turns on/off tracing info to the default location. if set = 0 tracing is off (this is the default)



The Complete Syntax of Lua

chunk ::= {stat [`;']}

block ::= chunk

stat ::= varlist1 `=' explist1
| functioncall
| do block end
| while exp1 do block end
| repeat block until exp1
| if exp1 then block {elseif exp1 then block} [else block] end
| return [explist1]
| break
| for `name' `=' exp1 `,' exp1 [`,' exp1] do block end
| for `name' `,' `name' in exp1 do block end
| function funcname `(' [parlist1] `)' block end
| local declist [init]

funcname ::= `name' | `name' `.' `name' | `name' `:' `name'

varlist1 ::= var {`,' var}

var ::= `name' | varorfunc `[' exp1 `]' | varorfunc `.' `name'

varorfunc ::= var | functioncall

declist ::= `name' {`,' `name'}

init ::= `=' explist1

explist1 ::= {exp1 `,'} exp

exp1 ::= exp

exp ::= nil | `number' | `literal' | var | function | upvalue
| functioncall | tableconstructor | `(' exp `)' | exp binop exp | unop exp

functioncall ::= varorfunc args | varorfunc `:' `name' args

args ::= `(' [explist1] `)' | tableconstructor | `literal'

function ::= function `(' [parlist1] `)' block end

parlist1 ::= `...' | `name' {`,' `name'} [`,' `...']

upvalue ::= `%' `name'

tableconstructor ::= `{' fieldlist `}' fieldlist ::= lfieldlist | ffieldlist | lfieldlist `;' ffieldlist | ffieldlist `;' lfieldlist lfieldlist ::= [lfieldlist1] ffieldlist ::= [ffieldlist1] lfieldlist1 ::= exp {`,' exp} [`,'] ffieldlist1 ::= ffield {`,' ffield} [`,'] ffield ::= `[' exp `]' `=' exp | `name' `=' exp

binop ::= `+' | `-' | `*' | `/' | `\^{ ' | `..'
| `<' | `<=' | `>' | `>=' | `==' | `\ { '=}
| and | or}

unop ::= `-' | not