Golly uses a statically embedded Lua interpreter (version 5.3.5) to execute .lua scripts. This lets you extend Golly's capabilities in lots of interesting ways.

  Example scripts
  Golly's scripting commands
  Cell arrays
  Rectangle arrays
  Using the gplus package
  NewCA.lua
  Potential problems
  Lua copyright notice

Example scripts

The Scripts folder supplied with Golly contains a number of example Lua scripts:

  1D.lua |  | — for exploring one-dimensional cellular automata
  3D.lua |  | — for exploring three-dimensional cellular automata
  breakout.lua |  | — shows how to use the overlay to create a game
  bricklayer.lua |  | — simple use of gplus to build a multipart pattern
  browse-patterns.lua |  | — lets you browse through patterns in a folder
  density.lua |  | — calculates the density of the current pattern
  draw-lines.lua |  | — lets you draw one or more straight lines
  envelope.lua |  | — uses multiple layers to show a pattern's history
  flood-fill.lua |  | — fills a clicked region with the current drawing state
  giffer.lua |  | — creates an animated GIF file using the selection
  goto.lua |  | — goes to a given generation
  gun-demo.lua |  | — constructs a few spaceship guns
  heisenburp.lua |  | — illustrates the use of cloned layers
  hexgrid.lua |  | — creates a true hexagonal grid
  invert.lua |  | — inverts all cell states in the current selection
  lifeviewer.lua |  | — displays patterns like LifeViewer (see details here)
  make-torus.lua |  | — makes a toroidal universe from the selection
  Margolus.lua |  | — for exploring rules using the Margolus neighborhood
  metafier.lua |  | — converts the current selection into a meta pattern
  move-object.lua |  | — lets you move a connected group of live cells
  move-selection.lua |  | — lets you move the current selection
  oscar.lua |  | — detects oscillating patterns, including spaceships
  overlay-demo.lua |  | — demonstrates most of the overlay functions
  p1100-MWSS-gun.lua |  | — extended use of gplus to build a complex pattern
  pd-glider.lua |  | — creates a set of pentadecathlon+glider collisions
  pop-plot.lua |  | — displays a plot of population versus time
  shift.lua |  | — shifts current selection by given x y
  slide-show.lua |  | — displays all patterns in the Patterns folder
  tile.lua |  | — tiles the selection with the pattern inside it
  tile-with-clip.lua |  | — tiles the selection with the clipboard pattern
  toLife.lua |  | — converts LifeHistory patterns to plain Life
  toLifeHistory.lua |  | — converts Life patterns to LifeHistory

To run one of these scripts, tick the Show Files item in the File menu, open the Scripts/Lua folder and then simply click on the script's name. You can also select one of the Run items in the File menu. For a frequently used script you might like to assign a keyboard shortcut to run it (see Preferences > Keyboard).

When Golly starts up it looks for a script called golly-start.lua in the same directory as the Golly application and then in a user-specific data directory (see the getdir command for the likely path on your system). If the script is found then it is automatically executed.

There are a number of ways to abort a running script. Hit the escape key, or click on the stop button in the tool bar, or select the Stop item in the Control menu.

Golly's scripting commands

This section describes all the g.* commands that can be used in a script after including this line:

  local g = golly()

Commands are grouped by function (filing, editing, control, viewing, layers and miscellaneous) or you can search for individual commands alphabetically:

  addlayer
  advance
  autoupdate
  check
  clear
  clone
  continue
  copy
  cut
  dellayer
  doevent
  duplicate
  empty
  error
  evolve
  exit
  fit
  fitsel
  flip
  getalgo
  getbase

  getcell
  getcells
  getclip
  getclipstr
  getcolor
  getcolors
  getcursor
  getdir
  getevent
  getfiles
  getgen
  getheight
  getinfo
  getlayer
  getmag
  getname
  getoption
  getpath
  getpop
  getpos
  getrect

  getrule
  getselrect
  getstep
  getstring
  getview
  getwidth
  getxy
  hash
  join
  load
  maxlayers
  millisecs
  movelayer
  new
  note
  numalgos
  numlayers
  numstates
  open
  opendialog
  overlay

  ovtable
  os
  parse
  paste
  putcells
  randfill
  reset
  rotate
  run
  save
  savechanges
  savedialog
  select
  setalgo
  setbase
  setcell
  setclipstr
  setcolor
  setcolors
  setcursor
  setdir

  setgen
  setlayer
  setmag
  setname
  setoption
  setpos
  setrule
  setstep
  settitle
  setview
  show
  shrink
  sleep
  step
  store
  transform
  update
  visrect
  warn

FILING COMMANDS

open(filename, remember=false)
  Open the given file and process it according to its type:

  - A HTML file (.htm or .html extension) is displayed in the help window.
  - A text file (.txt or .doc extension, or a name containing "readme") is opened in your text editor.
  - A script file (.lua or .py extension) is executed.
  - A zip file (.zip extension) is processed as described here.
  - Any other type of file is assumed to be a pattern file and is loaded into the current layer.

  A non-absolute path is relative to the location of the script. The 2nd parameter is optional (default = false) and specifies if the given pattern or zip file should be remembered in the Open Recent submenu, or in the Run Recent submenu if the file is a script.
  Example: g.open("my-patterns/foo.rle")

save(filename, format, remember=false)
  Save the current pattern in a given file using the specified format:

  "rle" |  | run length encoded (RLE)
  "rle.gz" |  | compressed RLE
  "mc" |  | macrocell
  "mc.gz" |  | compressed macrocell

  A non-absolute path is relative to the location of the script. The 3rd parameter is optional (default = false) and specifies if the file should be remembered in the Open Recent submenu. If the savexrle option is true then extended RLE format is used (see the Save Extended RLE item for details).
  Example: g.save("foo.rle", "rle", true)

opendialog(title, filetypes, initialdir, initialfname, mustexist=true)
  Present a standard Open dialog to the user and return the chosen path in a string. All parameters are optional; the default is an Open dialog showing the current directory, with a title of "Choose a file" and a file type of "All files (*)|*". If the 5th parameter (default = true) is set to false, the user can specify a new filename instead of choosing an existing file. If the given file type is "dir" then the dialog lets the user choose a directory rather than a file. If the user cancels the dialog, the return value will be an empty string.
  Example: local fname = g.opendialog("Open MCell File", "MCell files (*.mcl)|*.mcl", "C:\\Temp", "sample.mcl")
  Example: local dirname = g.opendialog("Choose a folder", "dir");

savedialog(title, filetypes, initialdir, initialfname, suppressprompt=false)
  Present a standard Save dialog to the user and return the chosen path in a string. All parameters are optional; the default is a Save dialog showing the current directory, with a title of "Choose a save location and filename" and a file type of "All files (*)|*". If a file already exists at the chosen location, an Overwrite? query will be displayed unless the 5th parameter (default = false) is set to true. If the user cancels the dialog, the return value will be an empty string.
  Example: local fname = g.savedialog("Save text file", "Text files (*.txt;*.csv)|*.txt;*.csv", "C:\\Temp", "Params.txt", 1)

load(filename)
  Read the given pattern file and return a cell array.
  Example: local blinker = g.load("blinker.rle")

store(cell_array, filename)
  Write the given cell array to the specified file in RLE format. If the savexrle option is true then extended RLE format is used (see the Save Extended RLE item for details).
  Example: g.store(cells, "foo.rle")

getdir(dirname)
  Return the path of the specified directory:

  "app" — the directory containing the Golly application.

  "data" — the user-specific data directory:

  On Linux: |  | ~/.golly/
  On Mac OS X: |  | ~/Library/Application Support/Golly/
  On Windows XP: |  | C:\Documents and Settings\username\Application Data\Golly\
  On Windows 7+: |  | C:\Users\username\AppData\Roaming\Golly\

  "temp" — the directory Golly uses to store various temporary files. All these files are deleted when Golly quits.

  "rules" — the user-specific rules directory set in Preferences > Control.

  "files" — the directory displayed by File > Show Files.

  "download" — the directory Golly uses to store downloaded files.

  In each case a full path is returned, terminated by the appropriate path separator for the current platform ("/" on Mac and Linux, "\" on Windows).
  Example: g.open(g.getdir("app").."Patterns/Life/Breeders/breeder.lif")

setdir(dirname, dirpath)
  Set the specified directory to the given path (which must be a full path to an existing directory). All the directory names listed above are allowed, except for "app", "data" and "temp".
  Example: g.setdir("download", "/path/to/my-downloads/")

getfiles(dirpath)
  Return the contents of the given directory as an array of strings. A non-absolute directory path is relative to the location of the script. File names are returned first, then subdirectory names. The latter names end with the platform-specific path separator ("/" on Mac and Linux, "\" on Windows). See slide-show.lua for an example.

getinfo()
  Return the comments from the current pattern.
  Example: local comments = g.getinfo()

getpath()
  Return the pathname of the current open pattern. Returns "" if the current pattern is new and has not been saved.
  Example: local path = g.getpath()

EDITING COMMANDS

new(title)
  Create a new, empty universe and set the window title. If the given title is empty then the current title won't change.
  Example: g.new("test-pattern")

cut()
  Cut the current selection to the clipboard.

copy()
  Copy the current selection to the clipboard.

clear(where)
  Clear inside (where = 0) or outside (where = 1) the current selection.
  Example: g.clear(1)

paste(x, y, mode)
  Paste the clipboard pattern at x,y using the given mode ("and", "copy", "or", "xor").
  Example: g.paste(0, 0, "or")

shrink(remove_if_empty=false)
  Shrink the current selection to the smallest rectangle enclosing all of the selection's live cells. If the selection has no live cells then the optional parameter specifies whether the selection remains unchanged or is removed.
  Example: if #g.getselrect() > 0 then g.shrink(true) end

randfill(percentage)
  Randomly fill the current selection to a density specified by the given percentage (1 to 100).
  Example: g.randfill(50)

flip(direction)
  Flip the current selection left-right (direction = 0) or top-bottom (direction = 1).

rotate(direction)
  Rotate the current selection 90 degrees clockwise (direction = 0) or anticlockwise (direction = 1).

evolve(cell_array, numgens)
  Advance the pattern in the given cell array by the specified number of generations and return the resulting cell array.
  Example: local newpatt = g.evolve(currpatt, 100)

join(cell_array1, cell_array2)
  Join the given cell arrays and return the resulting cell array. If the given arrays are both one-state then the result is one-state. If at least one of the given arrays is multi-state then the result is multi-state, but with one exception: if both arrays have no cells then the result is {} (an empty one-state array) rather than {0}. See below for a description of one-state and multi-state cell arrays.
  Example: local result = g.join(part1, part2)

transform(cell_array, x0, y0, axx=1, axy=0, ayx=0, ayy=1)
  Apply an affine transformation to the given cell array and return the resulting cell array. For each x,y cell in the input array the corresponding xn,yn cell in the output array is calculated as xn = x0 + x*axx + y*axy, yn = y0 + x*ayx + y*ayy.
  Example: local rot_blinker = g.transform(blinker, 0, 0, 0, -1, 1, 0)

parse(string, x0=0, y0=0, axx=1, axy=0, ayx=0, ayy=1)
  Parse an RLE or Life 1.05 string and return an optionally transformed cell array.
  Example: local blinker = g.parse("3o!")

putcells(cell_array, x0=0, y0=0, axx=1, axy=0, ayx=0, ayy=1, mode="or")
  Paste the given cell array into the current universe using an optional affine transformation and optional mode ("and", "copy", "not", "or", "xor").
  Example: g.putcells(currpatt, 6, -40, 1, 0, 0, 1, "xor")

getcells(rect_array)
  Return any live cells in the specified rectangle as a cell array. The given array can be empty (in which case the cell array is empty) or it must represent a valid rectangle of the form {x,y,width,height}.
  Example: local cells = g.getcells( g.getrect() )

getclip()
  Parse the pattern data in the clipboard and return the pattern's width, height, and a cell array. The width and height are not necessarily the minimal bounding box because the pattern might have empty borders, or it might even be empty.
  Example: local wd, ht, cells = g.getclip()

hash(rect_array)
  Return an integer hash value for the pattern in the given rectangle. Two identical patterns will have the same hash value, regardless of their location in the universe. This command provides a fast way to detect pattern equality, but there is a tiny probability that two different patterns will have the same hash value, so you might need to use additional (slower) tests to check for true pattern equality.
  Example: local h = g.hash( g.getrect() )

select(rect_array)
  Create a selection if the given array represents a valid rectangle of the form {x,y,width,height} or remove the current selection if the given array is {}.
  Example: g.select( {-10,-10,20,20} )

getrect()
  Return the current pattern's bounding box as an array. If there is no pattern then the array is empty ({}), otherwise the array is of the form {x,y,width,height}.
  Example: if #g.getrect() == 0 then g.show("No pattern.") end

getselrect()
  Return the current selection rectangle as an array. If there is no selection then the array is empty ({}), otherwise the array is of the form {x,y,width,height}.
  Example: if #g.getselrect() == 0 then g.show("No selection.") end

setcell(x, y, state)
  Set the given cell to the specified state (0 for a dead cell, 1 for a live cell).

getcell(x, y)
  Return the state of the given cell. The following example inverts the state of the cell at 0,0.
  Example: g.setcell(0, 0, 1 - g.getcell(0, 0))

setcursor(string)
  Set the current cursor according to the given string and return the old cursor string. The given string must match one of the names in the Cursor Mode menu.
  Example: local oldcurs = g.setcursor("Draw")

getcursor()
  Return the current cursor as a string (ie. the ticked name in the Cursor Mode menu).

CONTROL COMMANDS

run(numgens)
  Run the current pattern for the specified number of generations. Intermediate generations are never displayed, and the final generation is only displayed if the current autoupdate setting is true.
  Example: g.run(100)

step()
  Run the current pattern for the current step. Intermediate generations are never displayed, and the final generation is only displayed if the current autoupdate setting is true.

setstep(exp)
  Temporarily set the current step exponent to the given integer. A negative exponent sets the step size to 1 and also sets a delay between each step, but that delay is ignored by the run and step commands. Golly will reset the step exponent to 0 upon creating a new pattern, loading a pattern file, or switching to a different algorithm.
  Example: g.setstep(0)

getstep()
  Return the current step exponent.
  Example: g.setstep( g.getstep() + 1 )

setbase(base)
  Temporarily set the current base step to an integer from 2 to 2,000,000,000. The current exponent may be reduced if necessary. Golly will restore the default base step (set in Preferences > Control) upon creating a new pattern, loading a pattern file, or switching to a different algorithm.
  Example: g.setbase(2)

getbase()
  Return the current base step.

advance(where, numgens)
  Advance inside (where = 0) or outside (where = 1) the current selection by the specified number of generations. The generation count does not change.
  Example: g.advance(0, 3)

reset()
  Restore the starting pattern and generation count. Also reset the algorithm, rule, scale, location and step exponent to the values they had at the starting generation. The starting generation is usually zero, but it can be larger after loading an RLE/macrocell file that stores a non-zero generation count.

setgen(gen)
  Set the generation count using the given string. Commas and other punctuation marks can be used to make a large number more readable. Include a leading +/- sign to specify a number relative to the current generation count.
  Example: g.setgen("-1,000")

getgen(sepchar='\0')
  Return the current generation count as a string. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting string more readable. For example, g.getgen(',') would return a string like "1,234,567" but g.getgen() would return "1234567". Use the latter call if you want to do arithmetic on the generation count because then it's easy to convert the string to a number.
  Example: local gen = tonumber( g.getgen() )

getpop(sepchar='\0')
  Return the current population as a string. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting string more readable. For example, g.getpop(',') would return a string like "1,234,567" but g.getpop() would return "1234567". Use the latter call if you want to do arithmetic on the population count. The following example converts the population to a number.
  Example: local pop = tonumber( g.getpop() )

empty()
  Return true if the universe is empty or false if there is at least one live cell. This is much more efficient than testing getpop() == "0".
  Example: if g.empty() then g.show("All cells are dead.") end

numstates()
  Return the number of cell states in the current universe. This will be a number from 2 to 256, depending on the current algorithm and rule.
  Example: local maxstate = g.numstates() - 1

numalgos()
  Return the number of algorithms (ie. the number of items in the Set Algorithm menu).
  Example: local maxalgo = g.numalgos() - 1

setalgo(string)
  Set the current algorithm according to the given string which must match one of the names in the Set Algorithm menu.
  Example: g.setalgo("HashLife")

getalgo(index=current)
  Return the algorithm name at the given index in the Set Algorithm menu, or the current algorithm's name if no index is supplied.
  Example: local lastalgo = g.getalgo( g.numalgos() - 1 )

setrule(string)
  Set the current rule according to the given string. If the current algorithm doesn't support the specified rule then Golly will automatically switch to the first algorithm that does support the rule. If no such algorithm can be found then you'll get an error message and the script will be aborted.
  Example: g.setrule("b3/s23")

getrule()
  Return the current rule as a string in canonical format.
  Example: local oldrule = g.getrule()

getwidth()
  Return the width (in cells) of the current universe (0 if unbounded).
  Example: local wd = g.getwidth()

getheight()
  Return the height (in cells) of the current universe (0 if unbounded).
  Example: local ht = g.getheight()

VIEWING COMMANDS

setpos(x, y)
  Change the position of the viewport so the given cell is in the middle. The x,y coordinates are given as strings so the viewport can be moved to any location in the unbounded universe. Commas and other punctuation marks can be used to make large numbers more readable. Apart from a leading minus sign, most non-digits are simply ignored; only alphabetic characters will cause an error message. Note that positive y values increase downwards in Golly's coordinate system.
  Example: g.setpos("1,000,000,000,000", "-123456")

getpos(sepchar='\0')
  Return the x,y position of the viewport's middle cell in the form of two strings. The optional parameter (default = '\0') specifies a separator character that can be used to make the resulting strings more readable. For example, g.getpos(',') might return two strings like "1,234" and "-5,678" but g.getpos() would return "1234" and "-5678". Use the latter call if you want to do arithmetic on the x,y values, or just use the getposint() function defined in the gplus package.
  Example: local x, y = g.getpos()

setmag(mag)
  Set the magnification, where 0 corresponds to the scale 1:1, 1 = 1:2, -1 = 2:1, etc. The maximum allowed magnification is 5 (= 1:32).
  Example: g.setmag(0)

getmag()
  Return the current magnification.
  Example: g.setmag( g.getmag() - 1 )

fit()
  Fit the entire pattern in the viewport.

fitsel()
  Fit the current selection in the viewport. The script aborts with an error message if there is no selection.

visrect(rect_array)
  Return true if the given rectangle is completely visible in the viewport. The rectangle must be an array of the form {x,y,width,height}.
  Example: if not g.visrect({0,0,1,1}) then g.setpos("0","0") end

setview(wd, ht)
  Set the pixel width and height of the viewport (the main window will be resized accordingly).
  Example: g.setview(32*32, 32*30)

getview(index=-1)
  Return the pixel width and height of the viewport if the given index is -1 (the default), or the pixel width and height of the specified layer if the given index is an integer from 0 to numlayers() - 1.
  Example: local wd, ht = g.getview()

autoupdate(bool)
  When Golly runs a script this setting is initially false. If the given parameter is true then Golly will automatically update the viewport and the status bar after each command that changes the universe or viewport in some way. Useful for debugging scripts.
  Example: g.autoupdate(true)

update()
  Immediately update the viewport and the status bar, regardless of the current autoupdate setting. Note that Golly always does an update when a script finishes.

LAYER COMMANDS

overlay(command)
  Call a command to create, modify or delete the overlay, a rectangular area of pixels that can be displayed on top of the current layer.
  Example: g.overlay("create 400 300")

ovtable(command)
  Call a command to modify the overlay, a rectangular area of pixels that can be displayed on top of the current layer. This command takes a table as a parameter rather than a string (for improved performance) and supports the following overlay commands: fill, get, line, lines, paste, rgba and set.
  Example: g.ovtable{"line", 0, 0, 200, 300}

addlayer()
  Add a new, empty layer immediately after the current layer and return the new layer's index, an integer from 0 to numlayers() - 1. The new layer becomes the current layer and inherits most of the previous layer's settings, including its algorithm, rule, scale, location, cursor mode, etc. The step exponent is set to 0, there is no selection, no origin offset, and the layer's initial name is "untitled".
  Example: local newindex = g.addlayer()

clone()
  Like addlayer (see above) but the new layer shares the same universe as the current layer. The current layer's settings are duplicated and most will be kept synchronized so that a change to one clone automatically changes all the others. Each cloned layer does however have a separate viewport, so the same pattern can be viewed at different scales and locations (at the same time if layers are tiled).
  Example: local cloneindex = g.clone()

duplicate()
  Like addlayer (see above) but the new layer has a copy of the current layer's pattern. Also duplicates all the current settings but, unlike a cloned layer, the settings are not kept synchronized.
  Example: local dupeindex = g.duplicate()

dellayer()
  Delete the current layer. The current layer changes to the previous layer (unless layer 0 was deleted).

movelayer(fromindex, toindex)
  Move a specified layer to a new position in the layer sequence. The chosen layer becomes the current layer.
  Example: g.movelayer(1, 0)

setlayer(index)
  Set the current layer to the layer with the given index, an integer from 0 to numlayers() - 1.
  Example: g.setlayer(0)

getlayer()
  Return the index of the current layer, an integer from 0 to numlayers() - 1.
  Example: local currindex = g.getlayer()

numlayers()
  Return the number of existing layers, an integer from 1 to maxlayers().
  Example: if g.numlayers() > 1 then g.setoption("tilelayers",1) end

maxlayers()
  Return the maximum number of layers (10 in this implementation).

setname(string, index=current)
  Set the name of the given layer, or the current layer's name if no index is supplied.
  Example: g.setname("temporary")

getname(index=current)
  Return the given layer's name, or the current layer's name if no index is supplied.
  Example: if g.getname() == "temporary" then g.dellayer() end

setcolors(color_array)
  Set the color(s) of one or more states in the current layer and its clones (if any). If the given array contains a multiple of 4 integers then they are interpreted as state, red, green, blue values. A state value of -1 can be used to set all live states to the same color (state 0 is not changed). If the given array contains exactly 6 integers then they are interpreted as a color gradient from r1, g1, b1 to r2, g2, b2 for all the live states (state 0 is not changed). If the given array is empty then all states (including state 0) are reset to their default colors, depending on the current algorithm and rule. Note that the color changes made by this command are only temporary. Golly will restore the default colors if a new pattern is opened or created, or if the algorithm or rule changes, or if Preferences > Color is used to change any of the default colors for the current layer's algorithm.

  Example: g.setcolors({1,0,0,0, 2,0,0,0}) |  | # set states 1 and 2 to black
  Example: g.setcolors({-1,0,255,0}) |  | # set all live states to green
  Example: g.setcolors({255,0,0, 0,0,255}) |  | # live states vary from red to blue
  Example: g.setcolors({}) |  | # restore default colors

getcolors(state=-1)
  Return the color of a given state in the current layer as an array of the form

  { state, red, green, blue }

  or if the given state is -1 (or not supplied) then return all colors as

  { 0, r0, g0, b0, . . . N, rN, gN, bN }

  where N equals numstates() - 1. Note that the array returned by getcolors can be passed into setcolors; this makes it easy to save and restore colors.
  Example: local allcolors = g.getcolors()
  Example: local deadcolor = g.getcolors(0)

MISCELLANEOUS COMMANDS

os()
  Return the current operating system: "Windows", "Mac" or "Linux".
  Example: if g.os() == "Mac" then do_mac_stuff() end

millisecs()
  Return the number of milliseconds that have elapsed since Golly started up. The returned value is a floating point number.
  Example: local t1 = g.millisecs()

sleep(millisecs)
  Sleep for the given number of millisecs. Scripts with an event loop can call this command to avoid hogging the CPU when the script is idle.
  Example: g.sleep(5)

settitle(string)
  Set the window title to the given string. The original title will be restored when the script terminates.
  Example: g.settitle("running a search...")

setoption(name, value)
  Set the given option to the given value. The old value is returned to make it easy to restore a setting. Here are all the valid option names and their possible values:

  "autofit" |  | 1 or 0
  "boldspacing" |  | 2 to 1000 (cells)
  "drawingstate" |  | 0 to numstates()-1
  "fullscreen" |  | 1 or 0
  "hyperspeed" |  | 1 or 0
  "maxdelay" |  | 0 to 5000 (millisecs)
  "mindelay" |  | 0 to 5000 (millisecs)
  "opacity" |  | 1 to 100 (percent)
  "restoreview" |  | 1 or 0
  "savexrle" |  | 1 or 0
  "showallstates" |  | 1 or 0
  "showboldlines" |  | 1 or 0
  "showbuttons" |  | 0 to 4
  "showeditbar" |  | 1 or 0
  "showexact" |  | 1 or 0
  "showfiles" |  | 1 or 0
  "showgrid" |  | 1 or 0
  "showhashinfo" |  | 1 or 0
  "showicons" |  | 1 or 0
  "showlayerbar" |  | 1 or 0
  "showoverlay" |  | 1 or 0
  "showpopulation" |  | 1 or 0
  "showprogress" |  | 1 or 0
  "showscrollbars" |  | 1 or 0
  "showstatusbar" |  | 1 or 0
  "showtimeline" |  | 1 or 0
  "showtoolbar" |  | 1 or 0
  "smartscale" |  | 1 or 0
  "stacklayers" |  | 1 or 0
  "swapcolors" |  | 1 or 0
  "switchlayers" |  | 1 or 0
  "synccursors" |  | 1 or 0
  "syncviews" |  | 1 or 0
  "tilelayers" |  | 1 or 0

  Example: local oldgrid = g.setoption("showgrid", 1)

getoption(name)
  Return the current value of the given option. See above for a list of all the valid option names.
  Example: if g.getoption("autofit") == 1 then g.fit() end

setcolor(name, r, g, b)
  Set the given color to the given RGB values (integers from 0 to 255). The old RGB values are returned as 3 integers to make it easy to restore the color. Here is a list of all the valid color names and how they are used:

  "border" |  | color for border around bounded grid
  "paste" |  | color for pasting patterns
  "select" |  | color for selections (will be 50% transparent)
  algoname |  | status bar background for given algorithm

  Example: local oldr, oldg, oldb = g.setcolor("HashLife", 255, 255, 255)

getcolor(name)
  Return the current RGB values for the given color as 3 integers. See above for a list of all the valid color names.
  Example: local selr, selg, selb = g.getcolor("select")

getclipstr()
  Return the current contents of the clipboard as an unmodified string.
  Example: local illegalRLE = g.getclipstr()

setclipstr(string)
  Copy an arbitrary string (not necessarily a cell pattern) directly to the clipboard.
  Example: g.setclipstr(correctedRLE)

getstring(prompt, initial="", title="")
  Display a dialog box and get a string from the user. If the initial string is supplied it will be shown and selected. If the title string is supplied it will be used in the dialog's title bar. The script will be aborted if the user hits the dialog's Cancel button.
  Example: local n = tonumber( g.getstring("Enter a number:", "100") )

getevent(get=true)
  When Golly runs a script it initially handles all user events, but if the script calls getevent() then future events are put into a queue for retrieval via later calls. These events are returned in the form of strings (see below for the syntax). If there are no events in the queue then the returned string is empty. Note that the very first getevent() call will always return an empty string, but this isn't likely to be a problem because it normally occurs very soon after the script starts running. A script can call getevent(false) if it wants Golly to resume handling any further events. See flood-fill.lua for a good example.

  Key-down events are triggered when a key is pressed or autorepeats. The returned string is of the form "key charname modifiers" where charname can be any displayable ASCII character from '!' to '~' or one of the following names: space, home, end, pageup, pagedown, help, insert, delete, tab, return, left, right, up, down, or f1 to f24. If no modifier key was pressed then modifiers is none, otherwise it is some combination of alt, cmd, ctrl, meta, shift. Note that cmd will only be returned on a Mac and corresponds to the command key. The alt modifier corresponds to the option key on a Mac.

  Key-up events occur when a key is released and are strings of the form "kup charname".

  Mouse-down events in the current layer are strings of the form "click x y button modifiers" where x and y are integers giving the cell position of the click, button is one of left, middle or right, and modifiers is the same as above.

  Mouse-down events in a non-transparent pixel in the overlay are strings of the form "oclick x y button modifiers" where x and y are integers giving the pixel position in the overlay (0,0 is the top left pixel), button is one of left, middle or right, and modifiers is the same as above.

  Mouse-up events are strings of the form "mup button" where button is one of left, middle or right.

  Mouse wheel events in the current layer are strings of the form "zoomin x y" or "zoomout x y" where x and y are the mouse's pixel position in the viewport.

  Mouse wheel events in a non-transparent pixel in the overlay are strings of the form "ozoomin x y" or "ozoomout x y" where x and y are the mouse's pixel position in the overlay.

  File events are strings of the form "file filepath" where filepath is an absolute path. File events can be triggered in a number of ways: by clicking on a file in the left panel, by clicking an "open:" link in the Help window, by double-clicking a Golly-associated file, or by dropping a file onto the Golly window. It is up to the script to decide what to do with the file.

  The following examples show the strings returned after various user events:

  "key m none" |  | user pressed M key
  "key space shift" |  | user pressed space bar and shift key
  "key , altctrlshift" |  | user pressed comma and 3 modifier keys
  "kup left" |  | user released the left arrow key
  "click 100 5 left none" |  | user clicked cell at 100,5 with left button
  "click -10 9 middle alt" |  | user clicked cell with middle button and pressed alt key
  "click 0 1 right altshift" |  | user clicked cell with right button and pressed 2 modifiers
  "oclick 10 5 left none" |  | user clicked pixel at 10,5 in overlay with left button
  "mup left" |  | user released the mouse's left button
  "zoomout 10 20" |  | mouse wheel was used to zoom out from pixel in viewport
  "ozoomin 10 20" |  | mouse wheel was used to zoom in to pixel in overlay
  "file /path/to/foo.rle" |  | user tried to open the given file

  Example: local evt = g.getevent()

doevent(event)
  Pass the given event to Golly to handle in the usual manner (but events that can change the current pattern will be ignored). The given event must be a string with the exact same format as returned by the getevent command (see above). If the string is empty then Golly does nothing. Note that the cmd modifier corresponds to the command key on a Mac or the control key on Windows/Linux (this lets you write portable scripts that work on any platform).
  Example: g.doevent("key q cmd") -- quit Golly

getxy()
  Return the mouse's current grid position as a string. The string is empty if the mouse is outside the viewport or outside a bounded grid or over the translucent buttons, otherwise the string contains x and y cell coordinates separated by a space; eg. "-999 12345". See draw-lines.lua for a good example of how to use this command.
  Example: local mousepos = g.getxy()

show(message)
  Show the given string in the bottom line of the status bar. The status bar is automatically shown if necessary.
  Example: g.show("Hit any key to continue...")

error(message)
  Beep and show the given string in the bottom line of the status bar. The status bar is automatically shown if necessary.
  Example: g.error("The pattern is empty.")

warn(message, showCancel=true)
  Beep and show the given string in a modal warning dialog. Useful for debugging Lua scripts or displaying error messages. If showCancel is true (the default) then the dialog has a Cancel button as well as the usual OK button. Clicking OK will close the dialog and continue; clicking Cancel will close the dialog and abort the script.
  Example: g.warn("xxx = "..xxx)

note(message, showCancel=true)
  Show the given string in a modal information dialog. Useful for displaying multi-line results. If showCancel is true (the default) then the dialog has a Cancel button as well as the usual OK button. Clicking OK will close the dialog and continue; clicking Cancel will close the dialog and abort the script.
  Example: g.note("Line 1\nLine 2\nLine 3", false)

savechanges(query, message)
  Show a standard "save changes" dialog and return "yes", "no" or "cancel" depending on which button the user clicked.
  Example: local answer = g.savechanges("Save your changes?",
  "If you don't save, the changes will be lost.")

check(bool)
  When Golly runs a script this setting is initially true, which means that event checking is enabled. If the given parameter is false then event checking is disabled. Typically used to prevent mouse clicks being seen at the wrong time. This should only be done for short durations because the script cannot be aborted while the setting is false.
  Example: g.check(false)

continue(message)
  This function can be used to continue execution after pcall has detected some sort of error or the user has aborted the script. It's typically used to ensure some finalization code is executed. If not empty, the given message will be displayed in the status bar after the script has finished. See the end of envelope.lua for an example.

exit(message="")
  Exit the script with an optional error message. If a non-empty string is supplied then it will be displayed in the status bar along with a beep, just like the error command. If no message is supplied, or if the string is empty, then there is no beep and the current status bar message will not be changed.
  Example: if g.empty() then g.exit("There is no pattern.") end

Cell arrays

Some scripting commands manipulate patterns in the form of cell arrays. Golly supports two types of cell arrays: one-state and multi-state. A one-state cell array contains an even number of integers specifying the x,y coordinates for a set of cells, all of which are assumed to be in state 1:

  { x1, y1, . . . xN, yN }

A multi-state cell array contains an odd number of integers specifying the x,y,state values for a set of cells. If the number of cells is even then a padding integer (zero) is added at the end of the array to ensure the total number of integers is odd:

  { x1, y1, state1, . . . xN, yN, stateN } if N is odd
  { x1, y1, state1, . . . xN, yN, stateN, 0 } if N is even

All scripting commands that input cell arrays use the length of the array to determine its type. When writing a script to handle multi-state cell arrays you may need to allow for the padding integer, especially if accessing cells within the array. See tile.lua for example.

Note that all scripting commands return {} if the resulting cell array has no cells. They never return {0}, although this is a perfectly valid multi-state cell array and all commands can input such an array. For example, newarray = g.join(array1,{0}) can be used to convert a non-empty one-state array to multi-state.

One-state cell arrays are normally used in a two-state universe, but they can also be used in a universe with more than two states. A multi-state cell array can be used in a two-state universe, but only if the array's cell states are 0 or 1.

The ordering of cells within either type of array doesn't matter. Also note that positive y values increase downwards in Golly's coordinate system.

Rectangle arrays

Some commands manipulate rectangles in the form of arrays. An empty rectangle is indicated by an array with no items; ie. {}. A non-empty rectangle is indicated by an array containing four integers:

  { left, top, width, height }

The first two items specify the cell at the top left corner of the rectangle. The last two items specify the rectangle's size (in cells). The width and height must be greater than zero.

Using the gplus package

The gplus package supplied with Golly provides a high-level interface to many of Golly's built-in scripting commands. The package consists of a set of .lua files stored in the Scripts/Lua/gplus directory. The best way to learn how to use gplus is to look at some of the scripts supplied with Golly:

- See bricklayer.lua for how to use the pattern function to contruct a complicated pattern by combining simpler sub-patterns.
- See invert.lua for how to use the rect function to make it easier to manipulate rectangles.
- See p1100-MWSS-gun.lua for an extended example of an efficient script representation of a large complex pattern. This uses the pattern function to place different phases and orientations of each component object, and the put function to populate the resulting structure with spaceships.
- See shift.lua for how to use the split and validint functions to parse user input.

Here's a summary of the functions available after a script calls local gp = require "gplus" (see init.lua for all the implementation details):

  gp.int(x) |  | — return integer part of given floating point number
  gp.round(x) |  | — return rounded integer for given floating point number
  gp.min(a) |  | — return minimum value in given array
  gp.max(a) |  | — return maximum value in given array
  gp.drawline(x1,y1,x2,y2,z) |  | — draw a line of state z cells from x1,y1 to x2,y2
  gp.getedges(r) |  | — return left, top, right, bottom edges of given rectangle array
  gp.getminbox(p) |  | — return minimal bounding box of given cell array or pattern
  gp.validint(s) |  | — return true if given string is a valid integer
  gp.getposint() |  | — return viewport position as 2 integers
  gp.setposint(x,y) |  | — use given integers to set viewport position
  gp.split(s,sep) |  | — split given string into 1 or more substrings
  gp.equal(a1,a2) |  | — return true if given arrays have the same values
  gp.compose(S,T) |  | — return the composition of two transformations S and T
  gp.rect(r) |  | — return a table for manipulating a rectangle
  gp.pattern(p) |  | — return a table for manipulating a pattern
  gp.trace(msg) |  | — pass into xpcall so a runtime error will have a stack trace
  gp.timerstart(name) |  | — start a named timer
  gp.timersave(name) |  | — save the current elapsed time of the named timer
  gp.timervalue(name) |  | — get the last saved value of the named timer in milliseconds
  gp.timervalueall(precision) |  | — get a string with a list of all saved timer names and values in milliseconds and then reset all timers
  gp.timerresetall() |  | — reset all of the timers

Most of the supplied Lua scripts use gplus, but it isn't compulsory. You might prefer to create your own package for use in the scripts you write. If a script calls require "foo" then Golly will look for foo.lua in the same directory as the script, then it looks for foo/init.lua. If a script calls require "foo.bar" then Golly looks for foo/bar.lua. (If none of those files exist in the script's directory then Golly will look in the supplied Scripts/Lua directory, so scripts can always use the gplus package no matter where they are located.)

NewCA.lua

NewCA.lua is a gplus module that can be used by other Lua scripts to explore new cellular automata rules. To implement a new CA you need to create a .lua file that looks something like this:

      local g = golly()
      require "gplus.NewCA"

      SCRIPT_NAME = "MyCA"    -- must match the name of your .lua file
      DEFAULT_RULE = "XXX"    -- must be a valid rule in your CA
      RULE_HELP = "HTML code describing the rules allowed by your CA."

      function ParseRule(newrule)
          -- Parse the given rule string.
          -- If valid then return nil, the canonical rule string,
          -- the width and height of the grid, and the number of states.
          -- If not valid then just return an appropriate error message.

          ... parsing code for your rule syntax ...

          return nil, canonrule, wd, ht, numstates
          -- Note that wd and ht must be from 4 to 4000,
          -- and numstates must be from 2 to 256.
      end

      function NextPattern(currcells, minx, miny, maxx, maxy)
          -- Create the next pattern using the given parameters:
          -- currcells is a non-empty cell array containing the current pattern.
          -- minx, miny, maxx, maxy are the cell coordinates of the grid edges.
          -- This function must return the new pattern as a cell array.

          local newcells = {}

          ... code to create the next pattern in newcells ...

          -- delete the current pattern and add the new pattern
          g.putcells(currcells, 0, 0, 1, 0, 0, 1, "xor")
          g.putcells(newcells)

          return newcells
          -- Note that currcells and newcells are one-state cell arrays if
          -- g.numstates() == 2, otherwise they are both multi-state.
      end

      StartNewCA()

It should be possible to implement almost any CA that uses square cells with up to 256 states. NewCA.lua provides a lot of useful functionality:

- The interface is essentially the same as Golly. The only really new feature is a combined menu+tool bar that appears under the edit bar. It has some menus (File, Edit, View) on the left side and various buttons (Start, Reset, etc) on the right side, along with a slider for controlling the step size.
- Full Golly-like editing (cut/copy/paste/select/etc) including unlimited undo/redo. All of Golly's usual cursor modes are supported.
- Patterns can be saved as .rle files. These files can be opened via the File menu's Open Pattern command. You can also open a pattern stored in the clipboard via the Open Clipboard command (or by typing shift-O).
- Users can get help in various ways (type H or click the "?" button) and see documentation about the required rule syntax, the menu commands, a list of all the keyboard shortcuts, etc.
- Your script can run other Lua scripts to do searches, build patterns, etc. In particular, users can specify a script to be run whenever your script starts up. A startup script can do lots of customizations (add/modify keyboard shortcuts, change the color scheme, specify a different DEFAULT_RULE, add aliases for specific rules, etc).

There is of course a price to pay for all this flexibility, and that's speed. Don't expect your CA to run at Golly-like speeds! It won't really be practical to write a CA that supports very large neighborhoods (7x7 is about the limit).

To implement a new CA you'll typically need to write a couple of hundred lines of Lua code to parse the rule strings allowed by your CA and to calculate the next pattern. To help with this task, a couple of example scripts are supplied with Golly:

1D.lua lets you explore some one-dimensional rules. It supports all of Stephen Wolfram's 256 elementary rules (including the odd numbers), as well as totalistic rules with up to 4 states and a maximum range of 4.

The syntax for elementary rules is Wn where n is from 0 to 255. Totalistic rules are strings of the form CcKkRr where c is a code number from 0 to k^((2r+1)k-2r)-1, k is the number of states (2 to 4), and r is the range (1 to 4).

The ParseRule code sets NextPattern to either NextElementary or NextTotalistic, depending on the given rule. This is a useful technique that avoids the code in NextPattern becoming way too big and complicated.

1D.lua always generates from the bottom row of the current pattern. When it reaches the bottom row of the grid, it clears the grid, copies the bottom row to the top of the grid, and continues.

SetColors is redefined to use the same color scheme as in Wolfram's "A New Kind of Science". Note that the SetColors function uses g.setcolor commands to change the grid border and the status bar background to light blue.

1D.lua also redefines the RandomPattern function to create a single row of random cells at the top of the grid.

Margolus.lua lets you explore rules using the Margolus neighborhood. Rule strings are of the form Mn,n,n,... where there must be 16 comma-separated numbers with values from 0 to 15. MCell's syntax (MS,Dn;n;n;...) is also allowed, as are these aliases:

  bbm = M0,8,4,3,2,5,9,7,1,6,10,11,12,13,14,15 (the default rule)
  critters = M15,14,13,3,11,5,6,1,7,9,10,2,12,4,8,0
  tron = M15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,0

The ParseRule code sets NextPattern to either FastPattern or SlowPattern, depending on the given rule. FastPattern is used if the rule starts with M0, or if it starts with M15 and ends with 0. To avoid ugly strobing effects in the latter case, two alternating rules will be used: one rule for even-numbered generations and another rule for odd-numbered generations (similar to how Golly handles B0 rules).

The above two scripts have a number of features in common:

- Users can hit alt-R (option-R on a Mac) to create a random pattern with a random rule. This makes it easy to search for rules with interesting behavior.
- Both scripts use a toroidal grid with a default size of 500 x 500. For consistency with Golly, all rule strings can have an optional suffix like ":T400,300" or ":T400" to specify a desired grid size. (It's perfectly possible to support other topologies but you'd have to write a lot of messy code.)
- The ParseRule code allows entering an empty string as a quick way to switch to the default rule.
- Letters in a given rule can be entered in lower case, but the canonical version always uses upper case.
- Both scripts define a global aliases table so you can assign mnemonic names to specific rule strings.

It's probably a good idea to support these features in any new CA you might write, but it's not compulsory.

Potential problems

1. There are some important points to remember about Lua, especially when converting an existing Perl/Python script to Lua:

- Cell arrays and rectangle arrays start with index 1, not 0. This is necessary to be able to use Lua's length operator (#) and standard library functions like table.unpack.
- Lua's true and false are not equivalent to 1 and 0. In particular, "if 0" is true.
- Avoid calls like local x, y, wd, ht = g.getrect(). Only x will get a non-nil value (a rectangle array). You need to do local x, y, wd, ht = table.unpack(g.getrect()).
- When writing a complicated script it's a good idea to add the line require "gplus.strict" near the top. This will catch any undeclared global variables. When the script is working just remove or comment out that line.

More tips can be found at Lua Gotchas.

2. The escape key check to abort a running script is not done by Lua but by each g.* function. This means that very long Lua computations should call an occasional "no-op" like g.doevent("") to allow the script to be aborted in a timely manner.

3. When writing a script that creates a pattern, make sure the script starts with a new call (or, less useful, an open call that loads a pattern, or a save call) otherwise the script might create lots of temporary files or use lots of memory. From Golly's point of view there are two types of scripts:

- A script that calls new or open or save is assumed to be creating some sort of pattern, so when Golly sees these calls it clears any undo history and sets an internal flag that says "don't mark this layer as dirty and don't bother recording any further changes".
- A script that doesn't call new or open or save is assumed to modify the current pattern. Golly must record all the script's changes so that when it finishes you can select "Undo Script Changes" from the Edit menu. Generating changes (due to run or step calls) are stored in temporary files; all other changes are stored in memory.

Lua copyright notice

Copyright © 1994–2018 Lua.org, PUC-Rio.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.