Knowledgebase Article 90

Scripting with Lua

Since version ASC offers a Lua scripting interface.

Lua is a programming language that is targeted at easy integration into other programs and has been quite popular for various games recently.

Where to find documentation

There are lots of tutorials about the Lua language on the Internet, the one that I have been using is the one from Lua-Users.

ASC is using SWIG for interfacing between the C++ and the Lua part. This interface is generated from .i files, which are the best source to see which ASC functions are available to be used from Lua.

The most recent files are made available by the nightly build process:

common.i : Functions common to ASC and mapeditor
commands.i : ASC functions
/mapedcommands.i : Mapeditor functions

Instead of publishing a seperate command reference, which quickly be outdated, I recommend using these *.i files.

Since Lua exposes a subset of the internal classes of ASC, reading the overview of the data model in the Source documentation is also recommended.

A page with all kinds of Lua examples is maintained through the nightly build mechanism:
Lua Samples
This should serve as a good starting point to work with Lua in ASC.

How to use Lua

All ASC functions are inside a module called 'asc'

Hello World sample

The 'Hello World' program using the ASC infomessage function is:

asc.infoMessage('Hello World')

The infoMessage function can be found in the common.i

Iterating over all units

-- we will be counting the number of red units on the map (not including cargo)
counter = 0

-- get the active map map = asc.getActiveMap()

-- iterate over all fields of the map for y = 0,map:height()-1 do for x = 0,map:width()-1 do fld = map:getField(x,y)

-- check if there is a unit on the field if fld:getVehicle() then

-- check if the units belongs to red player (who is number 0) if fld:getVehicle():getOwner() == 0 then

-- increase our counter counter = counter + 1 end end end end

asc.infoMessage( counter .. ' red units on map' )

Please note that this does not include units that are inside buildings or transports

A bit of explanation:

You can find getActiveMap in common.i. There you see that the return result is of type GameMap

Further down, you can see the definition of class GameMap It has, among others, the methods height, width and getField.

getField in turn returns an object of type tfield, which has the functions getVehicle(), which returns a Vehicle or nil if there is no unit on the field.

class Vehicle is derived from ContainerBase, so it shares everything that ContainerBase offers and adds some additions things on its own. getOwner() is from ContainerBase.

Last change: Sat, 2009-06-20 21:13

search knowledgebase
browse knowledgebase