lua-users home
lua-l archive

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

On Sat, Mar 21, 2009 at 10:27 AM, Dmitry Maluka <> wrote:
> Hello!
> Briefly,
> In modern versions of Lua, host application works with Lua functions
> (and, more generally, tables and threads) only via stack (am I right?).
> Is there a way to store their values somewhere for future use?
> More specifically,
> I work on a computationally complex problem of constraint satisfaction
> (specifically, it's a university timetabling problem). I'm going to use
> Lua interface for constraints specifying.
> E.g., a call like
>        hard({Lecture, Lecture}, function(lec, lec2)
>                                   return (lec1.time ~= lec2.time
>                                        or ~=
>                                 end)
> creates a hard constraint that forbids placing 2 different events of
> type Lecture at the same room at the same time. It specifies a Lua
> function that checks the constraint.
> Such functions are called at each step of the search algorithm. Is
> there a way to call them immediately, without retrieving from somewhere
> every time?
You can store them in the registry and pull them back using the
reference value retrieved.

  /* Get or create function such that it's at top of stack */
 /* Get an integer reference into the registry table, any table is
valid, but the registry is a simple-to-access table for this */
 int reference = luaL_ref(L, LUA_REGISTRYINDEX);

 /* Get the value from the registry table to call */
 lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
 /* Operate on the value */

 /* Remove the value from the registry and mark the reference as re-usable */
luaL_unref(L, LUA_REGISTRYINDEX, reference);

Documentation on Registry Table:
luaL_ref :
Thomas Harning Jr.