seqlua

view seqlua.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 static int seqlua_ipairsaux_raw(lua_State *L) {
7 lua_Integer i;
8 luaL_checktype(L, 1, LUA_TTABLE);
9 i = luaL_checkinteger(L, 2) + 1;
10 lua_pushinteger(L, i);
11 lua_rawgeti(L, 1, i); // TODO: Lua 5.3 returns type
12 return lua_isnil(L, -1) ? 1 : 2;
13 }
15 static int seqlua_ipairsaux_index(lua_State *L) {
16 lua_Integer 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_call(lua_State *L) {
24 lua_pushinteger(L, luaL_checkinteger(L, 2) + 1);
25 lua_insert(L, 1); // integer on stack index 1
26 lua_settop(L, 2); // function on stack index 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 if (luaL_getmetafield(L, 1, "__ipairs")) {
39 lua_pushvalue(L, 1);
40 lua_call(L, 1, 3);
41 if (lua_type(L, -3) == LUA_TSTRING) {
42 const char *method = lua_tostring(L, -3);
43 if (!strcmp(method, "raw")) {
44 lua_pushcfunction(L, seqlua_ipairsaux_raw);
45 } else if (!strcmp(method, "index")) {
46 lua_pushcfunction(L, seqlua_ipairsaux_index);
47 } else if (!strcmp(method, "call")) {
48 lua_pushcfunction(L, seqlua_ipairsaux_call);
49 } else {
50 luaL_error(L, "Unexpected string returned by __ipairs metamethod");
51 }
52 lua_pushvalue(L, -3);
53 lua_pushinteger(L, 0);
54 }
55 } else {
56 int t = lua_type(L, 1);
57 if (t == LUA_TFUNCTION) {
58 lua_pushcfunction(L, seqlua_ipairsaux_call);
59 } else if (luaL_getmetafield(L, 1, "__index")) {
60 lua_pushcfunction(L, seqlua_ipairsaux_index);
61 } else {
62 luaL_checktype(L, 1, LUA_TTABLE);
63 lua_pushcfunction(L, seqlua_ipairsaux_raw);
64 }
65 lua_pushvalue(L, 1);
66 lua_pushinteger(L, 0);
67 }
68 return 3;
69 }
71 static int seqlua_concat(lua_State *L) {
72 const char *sep;
73 size_t seplen;
74 luaL_Buffer buf;
75 seqlua_Iterator iter;
76 sep = luaL_checklstring(L, 1, &seplen);
77 luaL_checkany(L, 2);
78 lua_settop(L, 3);
79 luaL_buffinit(L, &buf);
80 seqlua_iterloop(L, &iter, 2) {
81 lua_replace(L, 3);
82 if (seqlua_itercount(&iter) > 1) luaL_addlstring(&buf, sep, seplen);
83 luaL_tolstring(L, 3, NULL);
84 luaL_addvalue(&buf);
85 }
86 luaL_pushresult(&buf);
87 return 1;
88 }
90 int luaopen_seqlua(lua_State *L) {
91 lua_pushcfunction(L, seqlua_ipairs);
92 lua_setglobal(L, "ipairs");
93 lua_getglobal(L, "string");
94 lua_pushcfunction(L, seqlua_concat);
95 lua_setfield(L, -2, "concat");
96 return 0;
97 }

Impressum / About Us