lua-users home
lua-l archive

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


On Fri, Aug 23, 2013 at 06:12:59AM -0700, lua.greatwolf@mamber.net wrote:
> I'm resubmitting my original post in plain-text this time. Hopefully it'll 
> show up well enough and the mailing-list doesn't ruin it too badly:
> 
> I've been working on some bindings for lua to google's RE2 regex library
> and I got most of the important functions working. At the moment, I'm
> working on optimizing and reducing the overhead for the bindings.
> 
<snip>
>   // lua-re2.cpp
>   // a temporary function in my binding code used in the benchmark above
>   static int re2_countmatch(lua_State *L)
>   {
>     lua_settop(L, 2);
>     RE2 *re2obj = luaRE2_checkobject(L, 1);
>     StringPiece subject( luaL_checkstring(L, 2) );
> 

You should be using luaL_checklstring() here. You can pass a pointer _and_
the length to the StringPiece constructor:

	size_t n;
	const char *p = luaL_checklstring(L, 2, &n);
	StringPiece subject(p, (int)n);

Here's a snippet from the RE2 bindings I've written. These routines
implement the gmatch iterator:


static int luare2_nextmatch(lua_State *L) {
	RE2* pat = luare2_checkre2(L, lua_upvalueindex(1))->pattern;
	const char *txt;
	size_t len, pos;
	luare2_captures captures(pat->NumberOfCapturingGroups());
	bool match;

	txt = luaL_checklstring(L, lua_upvalueindex(2), &len);
	pos = luaL_checkinteger(L, lua_upvalueindex(3));

	if (pos >= len)
		return 0;

	StringPiece next(&txt[pos], (int)(len - pos));

	match = RE2::FindAndConsumeN(&next, *pat, captures, captures.count());

	if (!match)
		return 0; /* must return nil to terminate for-loop */

	pos = next.data() - txt;
	lua_pushinteger(L, pos);
	lua_replace(L, lua_upvalueindex(3));

	if (!captures.count()) {
		lua_pushboolean(L, true);

		return 1;
	} else
		return captures.push(L);
} /* luare2_nextmatch() */


static int luare2_gmatch(lua_State *L) {
	luare2_checkre2(L, 1);
	luaL_checkstring(L, 2);

	lua_settop(L, 2);

	lua_pushinteger(L, 0); /* initial offset into the string */

	lua_pushcclosure(L, luare2_nextmatch, 3);

	return 1;
} /* luare2_gmatch() */