[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Iterating proxy tables
- From: Dimitris Papavasiliou <dpapavas@...>
- Date: Thu, 2 Feb 2012 12:53:02 +0200
Hello,
I've been having this trouble for a while now but seeing tha Lua 5.2
would add the __next metamethod which would solve my problem I've been
putting it off. The situation is more or less common. Say you have a
C struct:
struct {
int a;
char *b;
} foo;
If you want to get/set the members of this struct from Lua you need to
set up an empty table with a metatable having __index and __newindex
metamethods like so:
__index:
k = lua_tostring (L, 2);
if (!strcmp (k, "a")) {
lua_pushnumber(L, foo.a);
} else if (!strcmp (k, "b")) {
lua_pushstring(L, foo.b));
}
return 1
__newindex:
k = lua_tostring (L, 2);
if (!strcmp (k, "a")) {
foo.a = lua_tonumber(L, 3);
} else if (!strcmp (k, "b")) {
foo.b = strdup(lua_tonumber(L, 3));
}
The code is more or less arbitrary of course and might be buggy but
it's just meant as an illustration. The problem is now that doing:
for k, v in pairs (fooproxy) do
print (k, v)
end
assuming that fooproxy is the proxy table in Lua, will do nothing as
the proxy is in fact empty but this can be solved by providing a
__next metatmethod. This metamethod which would also be implemented
in C needs to have a list of the keys. The rest is simple. My
problem is that I can't think of a way of providing the set of keys to
the __next metamethod other than explicitly listing them say like
char *keys[] = {"a", "b"}
and passing it to the __next metamethod as a light userdata somehow.
So my question is: is there some standard way of handling this problem
that would allow me to somehow list the keys only once so that I won't
have to remember to update they keys list each time I add a new key?
D.