# Programming in Lua

The library libipelua implements Lua bindings for many classes in Ipelib. If it is installed properly, it should suffice to say

    require "ipe"

in Lua to make use of these bindings.

These pages document the Lua bindings to Ipelib:

- Lua bindings for geometric objects
- Lua bindings for objects and attributes
- Lua bindings for Document, Page, and StyleSheet

When writing Ipelets in Lua, you have access to additional methods provided by the Ipe program itself:

- Lua bindings for Ipe
- Lua bindings for dialogs and menus

## Examples

Here is a Lua script that reads an Ipe document and then recenters each page on the paper:

    -- recenter.lua
    -- center objects on each page of the document

    require "ipe"

    inname, outname = ...

    if not outname then
      io.stderr.write("Usage: recenter.lua <inputfile> <outputfile>\n")
      return
    end

    doc = assert(ipe.Document(inname))

    -- make sure we have size information for text
    assert(doc:runLatex())

    layout = doc:styleSheet():find("layout")
    fs = layout.framesize

    for i,p in doc:pages() do
      box = ipe.Rect()
      for j = 1,#p do
        box:add(p:bbox(j))
      end
      nx = (fs.x - box:width()) / 2
      ny = (fs.y - box:height()) / 2
      trans = ipe.Vector(nx, ny) - box:bottomLeft()
      m = ipe.Translation(trans)
      for j = 1,#p do
        p:transform(j, m)
      end
    end
    doc:save(outname)

Here is a small Lua script that takes an Ipe document and exports each view separately in EPS format:

    -- splitviews.lua
    -- export each view of an Ipe document separately

    require "ipe"

    fname = ...
    if not fname then
      io.stderr:write("Usage: splitviews.lua <file>\n")
      return
    end

    i = fname:find("%.[^.]+$")
    if i then
      epsname = fname:sub(1,i-1)
    else
      epsname = fname
    end

    doc = assert(ipe.Document(fname))

    -- need latex information to save as Postscript
    assert(doc:runLatex())

    for i,p in doc:pages() do
      io.stderr:write("Saving page " .. i .. "\n")
      for j = 1, p:countViews() do
        out = epsname .. "-" .. i .. "-" .. j .. ".eps"
        io.stderr:write("Saving view " .. i .. "-" .. j .. " as " .. out .. "\n")
        doc:exportView(out, "eps", nil, i, j)
      end
    end