# Programming in Lua

The library libipelua implements Lua bindings for many classes in Ipelib. The bindings are available in Lua ipelets, as well as in Lua scripts executed using the ipescript program.

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. You can run this script as "ipescript recenter".

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

    if #argv ~= 2 then
      io.stderr:write("Usage: ipescript recenter <inputfile> <outputfile>\n")
      return
    end

    inname = argv[1]
    outname = argv[2]

    doc = assert(ipe.Document(inname))

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

    layout = doc:sheets():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

    if #argv ~= 1 then
      io.stderr:write("Usage: ipescript splitviews <file>\n")
      return
    end
    fname = argv[1]

    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

For more examples, have a look at the scripts in your Ipe installation, such as add-style.lua or update-styles.lua.