lua-users home
lua-l archive

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


Hi all,

I have a problem trying to write a Lua wrapper for the C syslog API. The problem is that ident in openlog(const char *ident, ...), a string that is prepended to every logged message, should be accessible by later calls to syslog().

Basically I need to keep a pointer to the ident string that should outlive the invocation of openlog(). Making ident static is not the way to go since we need an ident instance for every process linking against the library.

Digging in the mailing list I have come with this solution:

- in the library luaopen function: create a module environment to keep the ident string in it. - in l_openlog(): keep a copy of ident in a new userdatum and store it in the environment table - in l_closelog(: release any memory reserved for ident in a previous call to l_openlog()

Is this solution safe?
Is there an easier way?

int luaopen_syslog (lua_State *L)
{
	/* create a module environment to keep the ident string in it */
	lua_newtable(L);
	lua_replace(L, LUA_ENVIRONINDEX);
	luaL_register(L, "syslog", mylib);
	...
}

static int l_openlog(lua_State *L)
{
	...
	/* handle ident option */
	size_t len;
	const char *ident = luaL_checklstring(L, 1, &len);
	/* keep a copy of ident in a new userdatum */
	char *identcp = (char *)lua_newuserdata(L, len + 1);
	strcpy(identcp, ident);
	/* store it in our environment table */
	lua_setfield(L, LUA_ENVIRONINDEX, "ident");
	openlog(identcp, option, facility);
	return 0;
}


static int l_closelog(lua_State *L)
{
/* release any memory reserved for ident in a previous call to l_openlog */
	lua_pushnil(L);
	lua_setfield(L, LUA_ENVIRONINDEX, "ident");
	closelog();
	return 0;
}

--
Mit freundlichen Grüßen

Jesus Ruiz de Infante
(Entwicklung)
HALE electronic GmbH
Eugen-Müller-Straße 18, 5020 Salzburg, Austria
Tel:  +43 (662) 439011 0
Fax:  +43 (662) 439011 9
jesus.ruizdeinfante@hale.at
Firmenbuchnummer: FN 66801m HG Salzburg



--
Scanned by MailScanner.