seqlua

view seqlua.c @ 26:8ff86106e2fe

Curried function "filter" in README
author jbe
date Fri Aug 22 12:16:59 2014 +0200 (2014-08-22)
parents 44880bcfc323
children 367fc70acc15
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include "seqlualib.h"
5 static int seqlua_ipairsaux_raw(lua_State *L) {
6 lua_Integer i;
7 luaL_checktype(L, 1, LUA_TTABLE);
8 i = luaL_checkinteger(L, 2) + 1;
9 lua_pushinteger(L, i);
10 lua_rawgeti(L, 1, i); // TODO: Lua 5.3 returns type
11 return lua_isnil(L, -1) ? 1 : 2;
12 }
14 static int seqlua_ipairsaux_meta(lua_State *L) {
15 lua_Integer i;
16 i = luaL_checkinteger(L, 2) + 1;
17 lua_pushinteger(L, i);
18 lua_pushinteger(L, i);
19 lua_gettable(L, 1); // TODO: Lua 5.3 returns type
20 return lua_isnil(L, -1) ? 1 : 2;
21 }
23 static int seqlua_ipairsaux_func(lua_State *L) {
24 lua_pushinteger(L, luaL_checkinteger(L, 2) + 1);
25 lua_insert(L, 1);
26 lua_settop(L, 2);
27 lua_call(L, 0, LUA_MULTRET);
28 if (lua_isnoneornil(L, 2)) {
29 lua_settop(L, 0);
30 lua_pushnil(L);
31 return 1;
32 } else {
33 return lua_gettop(L);
34 }
35 }
37 static int seqlua_ipairs(lua_State *L) {
38 luaL_checkany(L, 1); // provides better error message
39 if (
40 lua_type(L, 1) == LUA_TFUNCTION ||
41 (luaL_getmetafield(L, 1, "__call") && (lua_pop(L, 1), 1))
42 ) {
43 lua_pushcfunction(L, seqlua_ipairsaux_func);
44 } else if (luaL_getmetafield(L, 1, "__index")) {
45 lua_pushcfunction(L, seqlua_ipairsaux_meta);
46 } else {
47 luaL_checktype(L, 1, LUA_TTABLE);
48 lua_pushcfunction(L, seqlua_ipairsaux_raw);
49 }
50 lua_pushvalue(L, 1);
51 lua_pushinteger(L, 0);
52 return 3;
53 }
55 static int seqlua_concat(lua_State *L) {
56 const char *sep;
57 size_t seplen;
58 luaL_Buffer buf;
59 seqlua_Iterator iter;
60 sep = luaL_checklstring(L, 1, &seplen);
61 luaL_checkany(L, 2);
62 lua_settop(L, 3);
63 luaL_buffinit(L, &buf);
64 seqlua_iterloop(L, &iter, 2) {
65 lua_replace(L, 3);
66 if (seqlua_itercount(&iter) > 1) luaL_addlstring(&buf, sep, seplen);
67 luaL_tolstring(L, 3, NULL);
68 luaL_addvalue(&buf);
69 }
70 luaL_pushresult(&buf);
71 return 1;
72 }
74 int luaopen_seqlua(lua_State *L) {
75 lua_pushcfunction(L, seqlua_ipairs);
76 lua_setglobal(L, "ipairs");
77 lua_getglobal(L, "string");
78 lua_pushcfunction(L, seqlua_concat);
79 lua_setfield(L, -2, "concat");
80 return 0;
81 }

Impressum / About Us