seqlua

view seqlua.c @ 31:4fc9090ada1d

Mention 3 extra elements on stack in README; Changed order of two instructions in seqlualib.c
author jbe
date Sat Aug 23 23:35:10 2014 +0200 (2014-08-23)
parents 367fc70acc15
children 3ff7cec8d3ce
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include "seqlualib.h"
5 static int seqlua_ipairsaux_index(lua_State *L) {
6 lua_Integer i = luaL_checkinteger(L, 2) + 1;
7 lua_pushinteger(L, i);
8 lua_pushinteger(L, i);
9 lua_gettable(L, 1); // TODO: Lua 5.3 returns type
10 return lua_isnil(L, -1) && i > luaL_len(L, 1) ? 1 : 2;
11 }
13 static int seqlua_ipairsaux_call(lua_State *L) {
14 lua_pushinteger(L, luaL_checkinteger(L, 2) + 1);
15 lua_insert(L, 1); // integer on stack index 1
16 lua_settop(L, 2); // function on stack index 2
17 lua_call(L, 0, LUA_MULTRET);
18 if (lua_isnoneornil(L, 2)) {
19 lua_settop(L, 0);
20 lua_pushnil(L);
21 return 1;
22 } else {
23 return lua_gettop(L);
24 }
25 }
27 static int seqlua_ipairs(lua_State *L) {
28 if (luaL_getmetafield(L, 1, "__ipairs")) {
29 lua_pushvalue(L, 1);
30 lua_call(L, 1, 3);
31 } else {
32 int t = lua_type(L, 1);
33 if (t == LUA_TFUNCTION) {
34 lua_pushcfunction(L, seqlua_ipairsaux_call);
35 } else {
36 if (t != LUA_TTABLE && !luaL_getmetafield(L, 1, "__index")) {
37 luaL_checktype(L, 1, LUA_TTABLE);
38 }
39 lua_pushcfunction(L, seqlua_ipairsaux_index);
40 }
41 lua_pushvalue(L, 1);
42 lua_pushinteger(L, 0);
43 }
44 return 3;
45 }
47 static int seqlua_concat(lua_State *L) {
48 const char *sep;
49 size_t seplen;
50 luaL_Buffer buf;
51 seqlua_Iterator iter;
52 sep = luaL_checklstring(L, 1, &seplen);
53 luaL_checkany(L, 2);
54 lua_settop(L, 3);
55 luaL_buffinit(L, &buf);
56 seqlua_iterloop(L, &iter, 2) {
57 lua_replace(L, 3);
58 if (seqlua_itercount(&iter) > 1) luaL_addlstring(&buf, sep, seplen);
59 luaL_tolstring(L, 3, NULL);
60 luaL_addvalue(&buf);
61 }
62 luaL_pushresult(&buf);
63 return 1;
64 }
66 int luaopen_seqlua(lua_State *L) {
67 lua_pushcfunction(L, seqlua_ipairs);
68 lua_setglobal(L, "ipairs");
69 lua_getglobal(L, "string");
70 lua_pushcfunction(L, seqlua_concat);
71 lua_setfield(L, -2, "concat");
72 return 0;
73 }

Impressum / About Us