seqlua

view seqlua.c @ 32:3ff7cec8d3ce

Do not respect __len metamethods
author jbe
date Sun Aug 24 00:00:43 2014 +0200 (2014-08-24)
parents 367fc70acc15
children 2a43e8ffbced
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_index(lua_State *L) {
15 lua_Integer i = luaL_checkinteger(L, 2) + 1;
16 lua_pushinteger(L, i);
17 lua_pushinteger(L, i);
18 lua_gettable(L, 1); // TODO: Lua 5.3 returns type
19 return lua_isnil(L, -1) ? 1 : 2;
20 }
22 static int seqlua_ipairsaux_call(lua_State *L) {
23 lua_pushinteger(L, luaL_checkinteger(L, 2) + 1);
24 lua_insert(L, 1); // integer on stack index 1
25 lua_settop(L, 2); // function on stack index 2
26 lua_call(L, 0, LUA_MULTRET);
27 if (lua_isnoneornil(L, 2)) {
28 lua_settop(L, 0);
29 lua_pushnil(L);
30 return 1;
31 } else {
32 return lua_gettop(L);
33 }
34 }
36 static int seqlua_ipairs(lua_State *L) {
37 if (luaL_getmetafield(L, 1, "__ipairs")) {
38 lua_pushvalue(L, 1);
39 lua_call(L, 1, 3);
40 } else {
41 int t = lua_type(L, 1);
42 if (t == LUA_TFUNCTION) {
43 lua_pushcfunction(L, seqlua_ipairsaux_call);
44 } else if (luaL_getmetafield(L, 1, "__index")) {
45 lua_pushcfunction(L, seqlua_ipairsaux_index);
46 } else {
47 luaL_checktype(L, 1, LUA_TTABLE);
48 lua_pushcfunction(L, seqlua_ipairsaux_index);
49 }
50 lua_pushvalue(L, 1);
51 lua_pushinteger(L, 0);
52 }
53 return 3;
54 }
56 static int seqlua_concat(lua_State *L) {
57 const char *sep;
58 size_t seplen;
59 luaL_Buffer buf;
60 seqlua_Iterator iter;
61 sep = luaL_checklstring(L, 1, &seplen);
62 luaL_checkany(L, 2);
63 lua_settop(L, 3);
64 luaL_buffinit(L, &buf);
65 seqlua_iterloop(L, &iter, 2) {
66 lua_replace(L, 3);
67 if (seqlua_itercount(&iter) > 1) luaL_addlstring(&buf, sep, seplen);
68 luaL_tolstring(L, 3, NULL);
69 luaL_addvalue(&buf);
70 }
71 luaL_pushresult(&buf);
72 return 1;
73 }
75 int luaopen_seqlua(lua_State *L) {
76 lua_pushcfunction(L, seqlua_ipairs);
77 lua_setglobal(L, "ipairs");
78 lua_getglobal(L, "string");
79 lua_pushcfunction(L, seqlua_concat);
80 lua_setfield(L, -2, "concat");
81 return 0;
82 }

Impressum / About Us