[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Enigma-devel] Lua API

From: Ronald Lamprecht
Subject: [Enigma-devel] Lua API
Date: Sun, 07 Oct 2007 23:21:51 +0200
User-agent: Thunderbird (Windows/20070728)

To all level authors,

This mailthread is about a new Lua API for levels as of Enigma 1.10.

In this rather long article, that may become part of future documentation,
I will first explain the problems that we are facing with the current API.
A draft proposal of the new API will introduce you to the new concepts.

I invite all level authors to contribute by proofreading the concepts,
pointing out critical points, making suggestions for additions and
improvements and especially in telling us their preference of the future
naming of functions, objects, etc.

Testers and help on updating the documentation are very welcome.

A partial "proof of concept" implementation is available with the current
svn repository trunk revision 897. Windows user can download this
development version from:


Two testlevels are available. The first being a demo level that shows
the new features on a playable level and the second one being a test
level with obfuscated examples of the new features for thorough
implementation testing:


The concept itself and this intro are available as files at:


Compatibility of the new API

All existing Enigma levels with compatibility of 0.92-1.0* will run
without modifications. The old API will be depreceated but will still
be supported for several upcoming releases.

By declaring a new level to Enigma compatibility 1.10 or above the
new API is selected exclusivly.

Remarks on the 1.0 Lua API

Every level author who used the Lua API 1.0 should be aware of many
inconsistencies in the naming of functions, objects and attributes.
If we succeed in identifying all these and other minor and major
flaws we have the unique opportunity to get rid of them.

But the driving force for the API reengineering is the aftermath of
the switch from Lua 4.2 to Lua 5.1 as being part of longterm strategic
goals like game saving and networking.

(Please refer to the given numbering on the single discussion points)

P1 - Booling the Booleans

a) Lua 4.* had no internal type for booleans. Comparisons did evaluate
to "nil" if false. All other values, even 0, were handled as true.

b) But the API defined in C manner two values "TRUE" of value "1"
and "FALSE" of value "0". Most old object attributes are bound
to these integer values.

c) Lua 5 did introduce a boolean type with values "true" and "false".
Object attributes introduced with Enigma 1.00 make use of these

This chaos does not only cause a lot of special code in the engine.
It is impossible to join a) and b) in a common value type that could
be passed on common messages. Objects like switches require an b-type
boolean on attributes like "on", but do answer with an a-type value
on callbacks. Level authors use wrong typed booleans which causes no
error messages in Lua. But the levels do not run as expected and cause
debugging sessions.

We prepared the engine for a unification of all booleans. But we have
to break the compatibility on the Lua API as we cannot seamlessly change
the types on the attributes and return values in a so called "type-free"
language like Lua. We would need new attribute and function names and
compatibility conversion functions. But the possible mixture of old
and new attributes and functions would just increase the chaos.

Thus the only clean solution is to drop the old API and redefine a
clean new one that can reuse names where it appropriate with clearly
defined boolean types.

P2 - Object reference validity and usability

The old API returns object references on set functions, callbacks and
GetNamedObject requests. They can be used as arguments for functions
like "SendMessage". But the references are temporary. They can not be
saved with a game and they are the most common cause of crashes. Storing
an object reference in a global Lua variable, killing the object and
issuing another command on the object does crash Enigma 1.0* for sure.
As objects are often killed without being noticed by the Lua part this
is a major problem.

Meanwhile I substituted the reference by a persistent id. This fixes the
crashes and prepares a future game save feature.

But still the object value usability is restricted. Not all functions
take object references as arguments as other require them. E.g. a callback
target requires a name string of a named object - a reference does not
work. On the other hand enigma.GetPos(obj) requires a reference - a name
string of a named object does not work. The API should take object
references whereever an object is referenced.

The other remaining problem is the consequence of accessing objects
that have been killed. The object id got invalid. But this is identical
to the current existing point P3:

P3 - Access to not existing Objects

Requesting a not existing Object returns a "nil" Lua value. It is not
defined and quite inconsistently implemented what happens if you access
such an object. F.e. "SendMessage" silently returns, where as "SetAttrib"
quits the level with a backtrace.

P4 - Position handling

A proper postion handling is missing. The levelauthor has to deal with
x, y coordinates himself. The return value from GetPos() does not match
the required argument of all set_object() functions. E.g.:

  item =  enigma.GetNamedObject("treasure")    -- need a object reference
  set_stone("st-glass1", enigma.GetPos(item))  -- works, x,y is expanded
                                               -- as last arg
  set_stone("st-laser-w", enigma.GetPos(item), {on=1})  -- error, as x,y
                                               --  does not get expanded

  if you want to set a stone with offset 1,1 to the item you have to write
  x,y = enigma.GetPos(item)
  set_stone("st-laser-w", x+1, y+1)  -- as you can not add positions

The consequence is a lot of unnecessary coordinate calculations and
transformations. The usage of absolute coordinates leads to patterns
and rooms that are hard to shift within the level on modifications.

P5 - Missing Object Grouping

The API does neither provide a container to handle groups of objects, nor
would any function be able to operate on several objects at once.

On map based level description the naming of identical objects that should
belong to a group is uncomfortable, as every objets needs to be assigned
a unique name. GetNamedObject() just returns one unique object, wildcards
are not supported.

Introduction of autonaming and wildcards causes inconsistencies to the
current API, even though it is unlikely that existing levels did make
use of the necessary special characters.

P6 - Oxyd stone flaws

Even though oxyd are standard stones you have to set them with a special
oxyd() funtion to get a standard coloring with pairs of oxyds of the
same color.

But this function does take the arguments oxyd(x, y, flavor, color). The
usual feature to add further attributes like "static" or user attributes
is missing.

The old API uses a quite unusual coding for the color. Even though the
color takes values from "0" to "7" they are not encoded as integers
but as strings. The Lua autoconversion of numbers to/from strings can
force the level author to very obscure and error-prone expressions, e.g.:

  oldcolor = 3  -- let both be given as integer
  newcolor = 5
  if (oldcolor == (enigma.GetAttrib(my_oxyd, "color") + 0)) then
      enigma.SetAttrib(oxyds[i], "color", "" .. newcolor)

In both cases you have to force Lua to choose the right type.
Otherwise you will fail.

As discussed on the forum the current oxyd_shuffle() function can
cause very unfair oxyd color distributions. Some times adjacent oxyds
are pairs what results in very low scores, other times a few level
might get unsolvable due to bad luck on the distribution.

P7 - Global Variables flaws

Variables are exported to Lua in 3 different namespaces (enigma, options,

Several mapping technologies are used causing inconsistent behaviour:

- some global variables like "ShowMoves" can be modified within Lua without
  causing an error - a read shows the modification, but the modification
  is never reflected within the engine (you have to set them before
  level initialization)
- other global variable that should be read only can be modified like
  difficult, options.Difficulty. The write does not affect the engine
  but may cause the level to run in the false mode within Lua.
- global variables are limited to numbers, bools - strings are not
  supported by tolua++

A general problem is the direct write to engine variables without
notification. Thus writes do only take affect on variables that are
polled on a regular basis.

P8 - Access to critical functions

The API provides several critical functions that either could prevent
levels from being compatible to future game saving or networking features,
or could disturb or even crash the current engine.

- enigma.date
  using a local date makes a level save and networkingincompatible

- display.*
  All functions besides SetFollowMode() are reserved for the app
  initialization and can damage the internal repositories.

- world.*
  All functions besides Resize() are reserved for the app initialization.
  Especially the second set of "Object" is totally incompatible to the
  the main API objects.

P9 - Signals - a peculiar target-actions

Besides the standard target-action feature the old API offers "signals"
as a mean to cause actions on several target at once without writing a
Lua callback function.

But this very useful feature uses a limiting API and as it is nearly not
documented just a few authors did make use of it.

The source object and the target have to specified by strings of type
"it(x,y)" that describe the position and the affected object type. Neither
object references nor object names were taken. But the main flaw of this
syntax is, that the signal will fail if the user moves or swaps the target.
Furtheron the addition of a Lua function as target is not possible.

P11 - Rubberband

Rubberbands are no standard objects. Once set it is impossible to access
them from Lua.

P12 - Loss of Identity

During some sort of pushs stones may currently be substituted by new
instances of the same class. This breaks object references and
attributes attached to these objects.

This is mainly a problem of the engine. But the API cannot make
guarantees about the liftime of object references and attributes as
long the engine has not be reengineered.

P13 - Naming Inconsistencies

The names used in the API are very inconsistent. There is no common
scheme. Level authors will have to look up the names every time:

- function, global attributes naming:
  Either in part of global Lua namespace or scattered in one of
  several used namespaces (enigma, display, world)
  Upper- and lowercase usage, underscore or sawtooth (set_floor,
- inconsistent Objectnames _ vs. - :
  "st-stoneimpulse_movable", "st-stoneimpulse-hollow"
  (who is able to remember all theses differences?)
- enigma.SetStone() not directly callable (needs an Object) - the
  user function is set_stone(; but enigma.GetStone() is the user
  function to get a stone reference.
- enigma.GetAttrib(obj, name) is one function for all object types,
  but we have set_stone(), set_item(),...

P14 - Advantages and Disadvantages of various Levelcoding Approaches

Looking at the basic API functions it is obvious that they are straight
forward mappings of existing internal functions/methods/variables. They
have not been designed for level coding demands. Writing a level based
just on these primitivs that set and modify a single object at once causes
huge and unmaintainable level sources that are unacceptable for inclusion
in the Enigma distribution.

Thus various authors did add libraries, wrote own functions to ease the
burden of coding levels.

Simple geometric based aggregate functions are included in the preloaded
init.lua. With functions like "fill_floor()" and "draw_border()" it is
possible to write simple levels quite efficiently. An example is the first
welcome level in levelpack Enigma I. But with every objects that is added
beyond the basic geometry the level grows by a line. The functions take
absolute coordinates. Thus any modification causes pain. Parsing and
interpretation of such geometric functions with an level editor is very

Thus most other approaches did introduce a declarative map based level
coding. Maps are easy to read and write by humans and editors. The storage
of maps is efficient. But the definition of the used map codes is not
supported by the API. Thus different authors made use of the means that
Lua offers:

"ant" and "nat" both make use of recursive functions for the map tile
definitions. Even though this is a powerful approach, recursive functions
are difficult to understand in their complexity, very difficult to parse
by an editor and in case of errors they produce backtraces that need the
full knowledge of their implementation to debug a simple problem caused
by a typo.

Some author like "duffy" did simplify the tile definiton by usage of a
simple "renderline()" function with a huge if clause that sets for
each tile type the objects using the basic API functions. The approach
does not allow to reuse tile definitions for other tile definitions.
This makes the if clause larger than necessary and causes inconsistencies
when modifications are not copied to all affected tiles.

None of the map-tile based approaches provides a protection for
incidential tile redefinitions - a common problem due to the limited
set of characters that can be used within the map. Fortunatley most maps
allow to use 2 or even more characters per tile.

Even though Enigma itself as well as Lua are both object based by their
very nature the API does not relect this. As Lua libraries cannot add
an object based extension to the API they had to use recursive functions.
But when I added the API function "enigma.IsSameObject()" Daniel asked
me why I did not implement the Lua operator "==" for Enigma objects.
At that point of time the other 1.00 release topics have been more urgent.
But I recognized that the object based approach can and should be improved.

Concept Lua API          (Draft 0.5)

C1 - Object Based Syntax   (coded - besides lines starting with a ".")

The new API provides successor functions for all basic functions of the
old API with simplified names and arguments. (As the naming of the
successor functions is not yet fixed just a few examples are listed. This
set of functions will be completed to ensure that all previous styles of
level programming are supported in the API as well).

The following example based description explains the idea of the
new object based syntax additions:

Namespace "en"

Any system object or function is addressable as "sysname" and "en.sysname"

Special value types:

  position      - a position within the world that can be described by an
                  x and y coordinate
object - an Enimga object like a stone, item, floor, rubberband,...
  world         - a singleton type for the world that contains all objects
  namedobjects  - a singleton type for the repository of all named objects
  group         - a list of objects
tile - a description of objects at a common grid position (floor,
                  item, stone, actor)
  tiles         - a singleton type for the repository of all tile instances

Special objects given at init:

  wo   world with map and global attributes of type <world>
  no   named object repository of type <namedobjects>
  ti   tile template repository of type <tiles>

Let "obj" be an example object reference of a stone/item/floor (type <object>).

Grid Positions are table/objects:

  pos = po(7, 3)            -- a function "po()"
  pos = po({7, 3})
  pos = obj                 -- every object is a valid position
  pos = po(12.3, 3.7)       -- position within a grid (for an actor)

Position constants
{7,3} -- a valid position for all arguments and operations (see caveats)

Access to x, y coordinates:

  x, y = pos.x, pos.y
  x, y = pos["x"], pos["y"]
  x, y = pos:xy()
  x, y = obj.x, obj.y
  x, y = obj:xy()
. x, y = GetXY(obj)

Position calculation

  pos = obj + {2,7}
  dpos = obj1 - obj2
  dpos2 = 2 * dpos

Center positions for set actors

  pos_centered1 = pos + {0.5, 0.5}
  pos_centered2 = #pos
  pos_centered3 = #obj
. pos_centered4 = Center(obj)

Round a position to a grid

  grid_pos = pos:grid()

Position comparison

  pos_centered1 == pos_centered2

Setting a single attribute of objects including global attributes of world:

  obj["attr_name"] = value
  wo["Brittleness"] = 7

. SetAttrib(obj, "attr_name", value)

Setting multiple attributes at once:

  obj:set({attr_name1=value1, attr_name2=value2})
. SetAttribs(obj, {attr_name1=value1, attr_name2=value2})

Requesting attributes of objects including global attributes of world:

  value = obj["attr_name"]
  value = wo["Brittleness"]
. value = GetAttrib(obj, "attr_name")

  if wo["IsDifficult"] then ... end

Reset an attribute to its default - "delete":

. obj["attr_name"] = nil

Creating a new object:

  wo[pos] = {"st_chess", color = 0, name="Atrax"}   -- on edge of grid pos
  wo[#pos] = {"ac_bug"}              -- actor centered on grid pos
  wo[pos] = {"#ac_bug"}              -- actor centered on grid pos
  wo[pos] = {"ac_bug", 0.3, 0.7}     -- actor with offsets to pos
  wo[my_floor] = {"it_wand"}         -- set an wand on top of a given foor

Naming an object:

  no["Atrax"] = obj

Consecutive naming of objects (building object groups)

  wo[pos] = {"st_chess", color = 0, name="Atrax#"}

For each call of the line above the new object will be named with a unique
  number appended after the "#" giving "Atrax#1", "Atrax#2", "Atrax#3", ...

Requesting an object:

  obj = it(pos)
  obj = it(x, y)
  obj = st(pos)
  obj = wo:it(pos)
my_item = it(my_floor) -- get the item that is on top of the given floor

  obj = no["Atrax"]

Killing an object:

  wo[pos] = {"it_nil"}

Comparing objects

  obj1 == obj2

Existance of an object

  -obj                -- unary minus operator on object
  if -obj then ...


  my_bolder:message("direction", WEST)

Classification of objects:

. obj:is("st_chess")
. obj:is("st")
. obj:is("st_chess_black")

Group of objects:

  group = no["Atrax#*"]            -- a group of all matching objects
                                   --   wildcards "*","?" allowed
  group = grp(obj1, obj2, obj3)
  group = grp({obj1, obj2, obj3})  -- a group of objects set up in a table

Many operations can be applied to groups

floor_group[friction] = 3.2 -- set attribute on all floors in the group
  wo[floor_group] = {"it-coin2"}   -- add some money on all floor positions

. wo[pos] = {"st_switch", target=door_group, action="onoff"} -- multitarget
. wo[pos] = {"st_switch", target="door#*", action="onoff"}

Group operations
  doors_lasers = doorgrp + lasergrp       -- join of two groups
  lasergrp     = doors_lasers - doorgrp   -- difference of two groups
  common_doors = doorgrp1 * doorgrp2      -- intersection of two groups

Setting and connecting two vortices:

. wo[{3,4}] = {"it_vortex", name="vortex1", target="vortex2"}
. wo[{8,6}] = {"it_vortex", name="vortex2", target="vortex1"}


  ti["  "] = {"fl_sand"}
  ti[" w"] = ti["  "] .. {"it_wand"}
  ti["  "] = {"fl_abyss"}   -- redefinition causes error to avoid common
                            --   mistakes

  wo[{3,4}] = ti[" w"]
  wo[{5,6}] = ti["  "] .. {"st_chess"}

  width, height = wo(ti, "  ", { -- second arg: default tile key that
  "########",                    --   defines the base, too - this example
  "##   w##",                    --   is 2 chars per tile/grid

Note: Tiles kann be used after the initialization as well:

function my_callback(sender)
    wo[sender] = ti[" w"]

Multipositions - draw lines and fill areas

. wo[pos1 .. pos2] = ti["  "]    -- fills the area spanned by pos1 and pos2

C2 - Object reference validity and usability   (done)

Objects existance and validity can be checked at via the "obj:exists()"
method or the operator "-obj". Not existing objects are still of type
object (not nil like in old API!). These "null" objects are not equal
concerning the Lua "==" comparison to any object, even themself.

Write access, kill of and messages to "null" objects are silently ignored.
World set objects to "null" object position is ignored, too. This allows
loops and group usage even with "null" targets without problems.

All read operations that return object specific values which are not
usable for group operations and can just be used with a single object
as target will throw an error if this object is a "null" object. The
application will no longer crash. Just a backtrace will be shown like
on other level exceptions.

C3 - Booleans and Nil

All boolean type attributes and values in the new API are Lua 5.0++
booleans with values "true" and "false". The engine internal value
representation takes boolean as another explicit type. Type mismatches
on transfer of boolean values from or to Lua will no longer occur.

Some attributes and values of the old API that did take values 0 and 1
may change to other types than boolean due to other API concepts.

Setting an attribute value to "nil" causes the value to be deleted.
Any further access returns the default value for the attribute.

C4 - Multitarget and Multiaction

The target-action paradigm is extended to a multitarget and multiaction
messaging system that is even configurable on the senders state.

Every object can take groups of objects as target:

my_switch = {"st_switch", target=no["my_doors#*"], action="open_close"}

Different targets can take different actions:

my_switch = {"st_switch", target={my_door, my_laser, "my_function"},
    action={"open_close", "on_off", "callback"}}

The default action for all functions is "callback", which can thus be

my_switch = {"st_switch", target="my_function"}

The default action for all objects is "toggle", which can thus be

my_switch = {"st_switch", target="my_laser"}

Every callback takes the arguments (state_value, sender) where
"state_value" is an integer value that represents the internal state
of the sender object. For switch like objects the state will be 0 for
"off" and 1 for "on". Other objects like fourswitch etc. will count the
their states from 0, 1, 2,...

For special cases, especially for editor based levels, the author can
specify different target/action behaviour based on the value of the
sender objects state. For each state the following special targets and
actions preceed the default target and actions given above:

my_switch = {"st_switch", target_0="my_door", action_0="close",
    target_1="my_laser", action_1="off"}

The multitarget feature is the successor of the old signal feature. In
contrast to signals that were bound to tile positions like "stone on
grid {15, 4}" the multitarget addresses objects themselves. The action
will find its target even when the user swaps it to another grid postion.

C5 - Renaming

The necessary API changes gives the unique opportunity to simplify
many old names and to make them consistence. None of names used above
is fixed. It is up to the level authors to agree on a naming scheme.

Note that valid Lua names start with letter or underscore and consist
just of these plus numbers.

Just the following rules and conditions need to be observed:

- Short 2 or 3 letter names for the namespace and the special objects
- System attribute and message names have to be valid Lua names not
  starting with underscore
- User attributes start with an underscore
- System attribute and method names are disjoint
- Identical system attributes or methods have identical behaviour for
  all objects
- User names for objects do not start with "$", do not contain "," and
  do not end with "#"
- Object Classnames should use a common scheme of underscore/hyphen
  usage: Either underscore only, or first hyphen and all other
  underscore,... (st_chess_black, st-chess_black, ...)

C6 - Global Variables   (coded)

Global variables are handled as attributes of the special world object
"wo". Write access on variables will be checked and can cause actions
if necessary. A write to a read only variable like "IsDifficult" will be
silently ignored.

C7 - Critical functions

All critical functions will be abolished to ensure that new levels
will be suited for upcoming features. For the very few existing levels
of the distribution that depend on such features exceptions will be
hardcoded that will keep these levels to conflict with the new features.

C8 - Oxyd   (coded besides shuffle)

The color attribute is an integer value (0, 1, ..., 7).

Oxyds can be set like any other stones. If no color attribute is
specified pairs of oxyds with the same color will be set.

To gurantee fair distributions and levels that are solvable the
author can declare minimum and maximum conditions an groups of
oxyds like:

OxydShuffle({grp1, max=0}, {{grp1, grp2}, min=2},
    {{grp1, grp3}, min=1, max=1})

C9 - Rubberband

Rubberband is an object that can be referenced and checked for existance.

C10 - Name inheritance

Items like it-seed, it-rubberband that change into stone or rubberband
objects on activation will inherit their name to the successor stone

C11 - Checkerboard Floor   (coded)

Every floor takes an attribute "checkerboard". If set to interger value
0 the floor will only be placed on grids with x+y being even, if set
to 1 the floor will be placed only on grids with x+y being uneven.

ti["x"] = ti({"fl_rough_red", checkerboard=0}) +
         {"fl_rough_blue", checkerboard=1}

generates an arbitrary shaped checkboardfloor on areas with tile "x"
on the world map.

C12 - Puzzle

Puzzles can be autoconfigured and shuffled by the engine. Besides the
single puzzle stones a dummy stone named "st_puzzle_auto" can be set.
All adjacent "st_puzzle_auto" and "st_puzzle_hollow" of the same color
will be configured to a puzzle with maximum number of connections:

ti["#"] = {"st_puzzle_auto"}
ti["*"] = {"st_puzzle_hollow"}

wo{ti," ",{
"  # ",
"### ",
" #  "}

results in a puzzle:


with the upper "+" being a hollow cross.

If any of the involved puzzle stones has an attribute "shuffle" set
to "true" the complete puzzle will shuffled. If the value of any
puzzle stone is an integer it will be taken as the number of permutations
to be applied. The maximum number of all values will be taken.

Shuffle occurs by permutation of rows and columns that a marble can
reverse. By default it is assumed that the user can permute rows and
columns on every side which is not blocked by a stone that is not hollow.

In case the puzzle is only accessable from one side the author can add
attributes "permute_v" and "permute_h" with boolean values to every
puzzle stone that does not follow the standard rule.

As hollow puzzle stones will never be permuted to the border of a puzzle
the author can ensure that every shuffle results in a solvable puzzle.


Index/member interpretation and operations of new types:

value = number|string|boolean|object|nil    add  |group|position ?

  x, y       - grid position access

. is()           - (string)        - test inheritance
  kill()         - ()              - kill object
  message()      - (string [, value]) - send message with an optional value
set() - (table) - set multiple attributes given in a table
                                     as key, value pairs

  attribute name       - set/get attribute

  other String not prefixed by "_"   - message

  valid Operations:
    +            - (object|position|table) + (object|position|table)
    -            - (object|position|table) - (object|position|table)
    #            - #object         -- center
    - (unary)    - -object         -- existance
    ==           - object == object


  x, y,          - grid position access

  grid()               - returns a position aligned to the grid
  xy()                 - returns x, y

  valid Operations:
    +            - (object|position|table) + (object|position|table)
    -            - (object|position|table) - (object|position|table)
    *            - (number|position) * (number|position)
    /            - position / number
    #            - # position
    ==           - position == position
.   ..           - position .. position


  $String              - reserved for future usage
  String               - named object access - returns nil if not existing
                       - name must not include wildcard chars *,?
  String*?             - get named group with wildcards *,?

  [object|position|table|group] = table|tile - write access to world grid
  [string]             - global world attribute read/write access

  ()             - (ti|function, string, table) -- initialization "wo(,,)"

  fl()           - (position|table|obj|(num,num)) - get floor at position
it() - (position|table|obj|(num,num)) - get item at position st() - (position|table|obj|(num,num)) - get stone at position

  init()         - (ti|function, string, table) -- method synonym for ()

1, 2, 3,... - positve integer as sequence index like table read access
  String               - on write: set attrib on members
                       - on access: call method or send message on object

  valid Operations:
    +                  - join of groups
    *                  - intersection of groups
    -                  - difference of groups
    #                  - length, inherited from table


  valid Operations:
   ..                   - concat tiles
   ti(table)            - new tile

  String               - table like read access with string  as index
- write only on not yet existing indices - no overwrite
                         assign (table|tile)

Global Functions  (to be defined)


. CreateWorld
. GetXY
. SetAttrib
. SetAttribs

. Center

Lua Caveats:

It is a basic LUA feature that the user has no real control about the used
variable types. This causes overall trouble:

a = "3"
b = "7"
c = 4
b - a == c          -- is true as    7 - 3 == 4
c + a == b          -- is false as   4 + 3 == 7  but 7 ~= "7"

A similar LUA problem may hit authors in the usage of position constants.
Expressions like {7,3} may be used anywhere as position arguments as they are autoconverted into positions. But care must be taken with direct calculations
and variable assignments of constant positions:

table = {7, 3}      -- this variable is a simple table with two numbers at
                    -- the indices 1 and 2 but it is not a position
wo[table] = obj     -- o.k. as the table gets now converted as an argument
pos = #table        -- is not a centerd position but a number with value 2
                    -- as it the length operation of a table
pos = table + {1,2} -- error as two tables cannot be added like positions
pos = obj + table   -- o.k. as obj is a position that forces an autoconvert
                    -- of the table

Another similar Lua caveat exists in the position comparison. Even though
you can use objects as position standins anywhere else the Lua comparison of
variables priorises the type comparison to the value comparison:

pos = po(3, 5)
wo[pos] = {"st-switch"}
obj = st(pos)
pos == obj          -- false as the types differ
pos == po(obj)      -- true as types and values are equal

Lua index syntax - different treatment of numbers, names and strings:

1, 2                        -- are valid Lua numbers
x, y, otto2, _myX           -- are valid Lua names
"$secret", "1", "fl-abyss"  -- are just Lua strings

x = 7
pos = po(3, 5)
pos["x"]          -- valid table like access to x coordinate
pos[x]            -- error as pos[7] is accessed
pos.x             -- valid member access that is equivalent to pos["x"]
obj["state"]      -- valid access to attribute "state"
obj[state] -- error as global variable "state" is first evaluated (nil)
obj.state         -- valid access to attribute "state"
tab[1]            -- valid table access to first entry
tab["1"]          -- table access to entry at key "1" which is not the first
                  --   table entry but likley nil.
tab.1             -- error - Lua needs a valid Lua-name as member




reply via email to

[Prev in Thread] Current Thread [Next in Thread]