lua-users home
lua-l archive

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


On Fri, 9 Nov 2001, Nick Trout wrote:

> > I have not so many knowledge of Lua and Lua/C bindings packages
> > like tolua, Luna, LuaWarapper and so on. And the question is: how quick
> > and fast do the *direct* binding between Lua data and C structures to access
> > this data from C?
> >
> > For example, I have "smart" Lua-based configuration file, like
> >
> >  Faults = {
> >       [1000] = {title="message1", type=20},
> >       [2000] = {title="message2", type=30}
> >  }
> >
> > And I want to access this data directly from my C-code, like
> >
> >  struct faults {
> >    char *title;
> >    int type;
> >  } *Faults;
> >  lua_dofile("faults.lua"); // run config file to init the above Faults
> > variable
> >  char *str = Faults[1000]->title; // and now get directly the field
> >
> > I walked through tolua docs (and alternate bindings packages), but they are
> > pointed more on access C-data/functions from Lua, and I need vice versa
> > functionality.
>
> Hi Ilja,
>     A solution would would be to expose a very simple C API to allow you to
> set your fault database/array and then do all of your configuration in Lua.

Along similar lines, perhaps with less work in the long run, is
something like this (I know it works with LuaSWIG, and I imagine with
tolua also):

in faults.h, which you also feed to LuaSWIG or tolua:

struct fault {
	char* title;
	int type;
};
fault*	new_fault();
/* implement via:
	{ return (fault*) malloc(sizeof(fault)); }
	or
	{ return new fault(); }	// C++
*/
void	add_fault(int index, fault* f);
fault*	get_fault(int index);

In Lua:

function create_faults(t)
-- pass in a table of fault constructors
	for index, initializers in t do
		-- create a fault struct
		local f = new_fault()

		-- initialize the members.
		for k,v in initializers do
			f[k] = v
		end

		-- add to the database.
		add_fault(index, f)
	end
end

create_faults{
	1000 = {title="message1", type=20},
	2000 = {title="message2", type=30}
}

In your C code:

	fault*	f = get_fault(1000);
	if (f) {
		printf("%s, %d\n", f.title, f.type);
	}

Untested code, but you get the idea -- basically you want to define
your data structures in C, and access them from Lua.  The wrapper
generator translates Lua's table access into structure member access.

-Thatcher