[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: cons cells for Lua
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 25 Mar 2004 14:41:09 -0300
To add more fun to the discussion, follows a small C module that adds
tuples to Lua. In some quick tests, they outperform tables both in
space and creation time, but are slower to access.
Manual:
a = newtuple(v1, v2, ..., vn) -- creates a new tuple
a(i) --> returns vi
a() --> returns v1, v2, ... vn
-- Roberto
#include <lua.h>
#include <lauxlib.h>
static int tuple_access (lua_State *L) {
int a = luaL_optint(L, 1, 0);
if (a == 0) { /* returns all elements? */
int i;
for (i=1; lua_type(L, lua_upvalueindex(i)) != LUA_TNONE; i++)
lua_pushvalue(L, lua_upvalueindex(i));
return i-1;
}
else {
luaL_argcheck(L, 1 <= a && lua_type(L, lua_upvalueindex(a)) != LUA_TNONE,
1, "invalid index");
lua_pushvalue(L, lua_upvalueindex(a));
return 1;
}
}
static int tuple_new (lua_State *L) {
int n = lua_gettop(L);
luaL_argcheck(L, n <= LUA_MINSTACK, n, "too many fields");
lua_pushcclosure(L, tuple_access, n);
return 1;
}
int luaopen_tuple (lua_State *L) {
lua_register(L, "newtuple", tuple_new);
return 0;
}