seqlua

view seqlualib.c @ 54:92ce3958aca7

Reverted last two commits
author jbe
date Wed Aug 27 00:10:47 2014 +0200 (2014-08-27)
parents 3362ec36cb09
children da4b9d6a5b7e
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include "seqlualib.h"
4 #include <string.h>
6 #define SEQLUA_ITERTYPE_IPAIRS 1
7 #define SEQLUA_ITERTYPE_CALL 2
8 #define SEQLUA_ITERTYPE_INDEX 3
9 #define SEQLUA_ITERTYPE_RAW 4
11 void seqlua_iterinit(lua_State *L, seqlua_Iterator *iter, int idx) {
12 if (luaL_getmetafield(L, idx, "__ipairs")) {
13 lua_pushvalue(L, idx);
14 lua_call(L, 1, 3);
15 if (lua_type(L, -3) == LUA_TSTRING) {
16 const char *method = lua_tostring(L, -3);
17 if (!strcmp(method, "raw")) {
18 iter->itertype = SEQLUA_ITERTYPE_RAW;
19 } else if (!strcmp(method, "index")) {
20 iter->itertype = SEQLUA_ITERTYPE_INDEX;
21 } else if (!strcmp(method, "call")) {
22 iter->itertype = SEQLUA_ITERTYPE_CALL;
23 } else {
24 luaL_error(L, "Unexpected string returned by __ipairs metamethod");
25 }
26 iter->idx = lua_gettop(L) - 1;
27 } else {
28 iter->itertype = SEQLUA_ITERTYPE_IPAIRS;
29 }
30 } else {
31 if (lua_type(L, idx) == LUA_TFUNCTION) {
32 iter->itertype = SEQLUA_ITERTYPE_CALL;
33 } else if (luaL_getmetafield(L, idx, "__index")) {
34 lua_pop(L, 1);
35 iter->itertype = SEQLUA_ITERTYPE_INDEX;
36 } else {
37 luaL_checktype(L, idx, LUA_TTABLE);
38 iter->itertype = SEQLUA_ITERTYPE_RAW;
39 }
40 // always occupy 3 stack indicies
41 lua_pushnil(L);
42 lua_pushnil(L);
43 lua_pushnil(L);
44 iter->idx = idx;
45 }
46 iter->L = L;
47 iter->i = 0;
48 }
50 int seqlua_iternext(seqlua_Iterator *iter) {
51 lua_State *L = iter->L;
52 lua_Integer i = ++iter->i;
53 switch (iter->itertype) {
54 case SEQLUA_ITERTYPE_IPAIRS:
55 lua_pushvalue(L, -3);
56 lua_pushvalue(L, -3);
57 lua_pushvalue(L, -3);
58 lua_call(L, 2, 2);
59 if (lua_isnil(L, -2)) {
60 lua_pop(L, 5);
61 return 0;
62 }
63 lua_remove(L, -3);
64 return 1;
65 case SEQLUA_ITERTYPE_CALL:
66 lua_pushvalue(L, iter->idx);
67 lua_call(L, 0, 1);
68 break;
69 case SEQLUA_ITERTYPE_INDEX:
70 lua_pushinteger(L, i);
71 lua_gettable(L, iter->idx);
72 break;
73 case SEQLUA_ITERTYPE_RAW:
74 lua_rawgeti(L, iter->idx, i);
75 break;
76 }
77 if (lua_isnil(L, -1)) {
78 lua_pop(L, 4);
79 return 0;
80 }
81 return 1;
82 }

Impressum / About Us