lua-users home
lua-l archive

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


Hello!

I have just released my first luarock, a port of the UW Cassowary Constraint Solving Toolkit. Hopefully I got everything right...

Cassowary is "an incremental constraint solving toolkit that efficiently solves systems of linear equalities and inequalities." Basically, it solves equations for you. This is incredibly useful in UI work, when you might want widget A to be twice the width of widget B but the total width of A and B to be not more than 500 pixels; this is why Apple uses it to lay out the UI of OS X applications.

Here's an example:

  cassowary = require("cassowary")

  -- Create a new solver object
  local solver = cassowary.SimplexSolver();

  -- Create lua variables to represent x and y
  local x = cassowary.Variable({ name = 'x' });
  local y = cassowary.Variable({ name = 'y' });

  -- Let's encode some expressions:

  --    x < y
  solver:addConstraint(cassowary.Inequality(x, "<=", y))

  --    y = x + 3
  solver:addConstraint(cassowary.Equation(y, cassowary.plus(x, 3)))

  --    either x = 10 or y = 10
  solver:addConstraint(cassowary.Equation(x, 10, cassowary.Strength.weak))
  solver:addConstraint(cassowary.Equation(y, 10, cassowary.Strength.weak))

  -- The solver automatically tries to resolve the current situation
  -- whenever constraints are added, so all we need to do is look
  -- at the values:

  print("x = "..x.value)
  print("y = "..y.value)

Depending on the phase of the moon, you will either see:

x=7
y=10

or

x=10
y=13


This port is itself a port of the Javascript port at https://github.com/slightlyoff/cassowary.js but any errors are almost certainly my responsibility. (Not that I understand what the code is doing, I'm just mindlessly translating the language.)

I'll be using it to improve the way that text frames are declared in my SILE typesetting engine ( https://github.com/simoncozens/sile ) but I hope it's useful to others as well. I'm sure those embedding lua into games can find interesting uses for it. Anyway, have fun.

Simon