[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Lua API Help
- From: Eric Tetz <erictetz@...>
- Date: Sun, 28 Apr 2002 19:40:34 -0700 (PDT)
I'm trying to write code to iterate over files and registry
keys using a for loop iterator in Lua 4.1w4. However, my C
code always seem to be outperformed by Lua code. A simple
example:
function iterator(max)
local val = 0
return function()
if val < max then
val = val + 1
return val
end
end
end
for i in iterator(10) do -- 1 to 10
print(i)
end
If I try to write 'iterator' via the C API, it is *slower*
than the Lua code. Here's my C translation:
int lua_iterator_next(lua_State* L)
{
int max = (int) lua_tonumber(L, lua_upvalueindex(1));
int cur = (int) lua_tonumber(L, lua_upvalueindex(2));
if (cur < max)
{
++cur;
lua_pushnumber(L, cur);
lua_replace(L, lua_upvalueindex(2));
lua_pushnumber(L, cur);
return 1;
}
return 0;
}
int lua_iterator_create(lua_State* L)
{
lua_pushvalue (L,1); // arg is 'max', make it first upvalue
lua_pushnumber(L,0); // next upvalue is our 'current value'
lua_pushcclosure(L, lua_iterator_next, 2);
return 1;
}
...
lua_registry(L, "iterator", lua_iterator_create);
Testing with a simple for loop 'for i in iterator(200000) do
end', I find the Lua code is roughly 25% faster than the C
code. What am I doing wrong?
Cheers,
Eric
__________________________________________________
Do You Yahoo!?
Yahoo! Health - your guide to health and wellness
http://health.yahoo.com