Skip to content
This repository has been archived by the owner on Nov 4, 2023. It is now read-only.

Commit

Permalink
Merge pull request #63 from justincormack/pairs
Browse files Browse the repository at this point in the history
__pairs/__ipairs support
  • Loading branch information
jmckaskill committed Oct 24, 2013
2 parents f2d0376 + 2122fdd commit 1473dc6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
PKG_CONFIG=pkg-config
LUA=lua

LUA_CFLAGS=`$(PKG_CONFIG) --cflags lua5.1 2>/dev/null || $(PKG_CONFIG) --cflags lua`
LUA_CFLAGS=`$(PKG_CONFIG) --cflags lua5.2 2>/dev/null || $(PKG_CONFIG) --cflags lua`
SOCFLAGS=-fPIC
SOCC=$(CC) -shared $(SOCFLAGS)
CFLAGS=-fPIC -g -Wall -Werror $(LUA_CFLAGS) -fvisibility=hidden -Wno-unused-function --std=gnu99
Expand Down
36 changes: 36 additions & 0 deletions ffi.c
Original file line number Diff line number Diff line change
Expand Up @@ -1924,6 +1924,40 @@ static int cdata_len(lua_State* L)
return luaL_error(L, "type %s does not implement the __len metamethod", lua_tostring(L, -1));
}

static int cdata_pairs(lua_State* L)
{
struct ctype ct;
int ret;

lua_settop(L, 1);
to_cdata(L, 1, &ct);

ret = call_user_op(L, "__pairs", 1, 2, &ct);
if (ret >= 0) {
return ret;
}

push_type_name(L, 2, &ct);
return luaL_error(L, "type %s does not implement the __pairs metamethod", lua_tostring(L, -1));
}

static int cdata_ipairs(lua_State* L)
{
struct ctype ct;
int ret;

lua_settop(L, 1);
to_cdata(L, 1, &ct);

ret = call_user_op(L, "__ipairs", 1, 2, &ct);
if (ret >= 0) {
return ret;
}

push_type_name(L, 2, &ct);
return luaL_error(L, "type %s does not implement the __ipairs metamethod", lua_tostring(L, -1));
}

static int cdata_add(lua_State* L)
{
struct ctype lt, rt, ct;
Expand Down Expand Up @@ -2846,6 +2880,8 @@ static const luaL_Reg cdata_mt[] = {
{"__tostring", &cdata_tostring},
{"__concat", &cdata_concat},
{"__len", &cdata_len},
{"__pairs", &cdata_pairs},
{"__ipairs", &cdata_ipairs},
{NULL, NULL}
};

Expand Down
10 changes: 10 additions & 0 deletions test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -844,5 +844,15 @@ local tp = ffi.metatype("struct newtest", {__new =
local v = tp(1, 2, 3)
assert(v.a == 1 and v.b == 2 and v.c == 3)

-- tests for __pairs and __ipairs; not iterating just testing what is returned
local tp = ffi.metatype("struct newtest",
{__pairs = function(tp) return tp.a, tp.b end, __ipairs = function(tp) return tp.b, tp.c end}
)
local v = tp(1, 2, 3)
x, y = pairs(v)
assert(x == 1 and y == 2)
x, y = ipairs(v)
assert(x == 2 and y == 3)

print('Test PASSED')

0 comments on commit 1473dc6

Please sign in to comment.