[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Writing Iterator in C
- From: Ralph Hempel <rhempel@...>
- Date: Wed, 31 Dec 2008 10:21:33 -0500
I have a C function that I would like to rewrite as an
iterator, but I'm having great difficulty in reproducing
the results that I get with my pure Lua test program.
I've read the appropriate chapters in PiL and the reference manual..
To test my understanding (or lack thereof) I
wrote a little test harness in pure Lua, like so:
This function will return the string x and a true or false flag
depending on wether the length of the string in x is even or odd.
n is always nil and the function returns nil when the length of
the string is 10 or greater.
function fooIter(n,x)
local i = string.len(x)
if i < 10 then
if 0 == i%2 then
return(x,true)
else
return(x,false)
end
end
return(nil)
end
Then the constructor:
function foo(s)
return(fooIter,nil,s)
end
And the harness, which appends an x or an o to the string depending
on the result of the iterator...
for p,s in foo("d") do
if( s ) then
p = p .. "o"
else
p = p .. "x"
end
end
Note that p (the control variable) is changed in the body
of the for loop, and this works fine in pure Lua.
However, when I rewrite the iterator and factory in C, I don't
get the expected results. Changing the value of p in thebody
of the for loop does not work as expected.
(This iterator does not check for length of 10, I know...)
static int fooIter (lua_State *L) {
size_t len;
const char *string = luaL_optlstring(L, 2, NULL, &len);
if( (NULL != string) ) {
// String that we're using is already on the top of the stack!
lua_pushboolean( L, len % 2 );
} else {
lua_pushnil( L );
lua_pushnil( L );
}
return(2);
}
static int foo (lua_State *L) {
lua_pushcclosure(L, fooIter, 0);
lua_pushnil( L );
lua_pushvalue( L, 1 );
return(3);
}
Am I doing something really stupid that's keeping this from working
the way I want it to?
Ralph