Пример #1
0
void merger_open_api( lua_State *L )
{
   /* Create the map interface. */
   lua_newuserdata( L, sizeof(void*) );
   
   /* Create the metatable for it. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_map_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_map_newindex );
   lua_setfield( L, -2, "__newindex" );
   
   lua_setmetatable( L, -2 );
   
   lua_setglobal( L, "map" );
   
   /* Create the rooms[] interface. */
   lua_newuserdata( L, sizeof(void*) );
   
   /* Create the metatable for it. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_rooms_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setmetatable( L, -2 );
   lua_setglobal( L, "rooms" );
   
   /* Create the room metatable, and store it for later use. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_room_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_room_equality );
   lua_setfield( L, -2, "__eq" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_room_metatable" );
   
   /* Create the exits metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_exits_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_exits_call );
   lua_setfield( L, -2, "__call" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_exits_metatable" );
   
   /* Create the exit metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_exit_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_exit_metatable" );
   
   /* Create the special exits metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_spexits_index );
   lua_setfield( L, -2, "__index" );
   lua_pushcfunction( L, merger_spexits_call );
   lua_setfield( L, -2, "__call" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_spexits_metatable" );
   
   /* Create the special exit metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_spexit_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_spexit_metatable" );
   
   /* Create area metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_area_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_area_metatable" );
   
   /* Create environment metatable. */
   lua_newtable( L );
   lua_pushcfunction( L, merger_environment_index );
   lua_setfield( L, -2, "__index" );
   
   lua_setfield( L, LUA_REGISTRYINDEX, "merger_environment_metatable" );
}
Пример #2
0
static void dns_cb(struct dns_ctx *ctx, void *result, void *data) {
  int r = dns_status(ctx);
  dns_lookup_ctx_t *dlc = data;
  struct dns_parse p;
  struct dns_rr rr;
  unsigned nrr = 0;
  unsigned char dn[DNS_MAXDN];
  const unsigned char *pkt, *cur, *end;
  lua_State *L;

  if(!dlc->active) goto cleanup;
  if(!result) goto cleanup;

  L = dlc->ci->coro_state;

  pkt = result; end = pkt + r; cur = dns_payload(pkt);
  dns_getdn(pkt, &cur, end, dn, sizeof(dn));
  dns_initparse(&p, NULL, pkt, cur, end);
  p.dnsp_qcls = 0;
  p.dnsp_qtyp = 0;

  while(dns_nextrr(&p, &rr) > 0) {
    const char *fieldname = NULL;
    char buff[DNS_MAXDN], *txt_str, *c;
    int totalsize;
    const unsigned char *pkt = p.dnsp_pkt;
    const unsigned char *end = p.dnsp_end;
    const unsigned char *dptr = rr.dnsrr_dptr;
    const unsigned char *dend = rr.dnsrr_dend;
    unsigned char *dn = rr.dnsrr_dn;
    const unsigned char *tmp;

    memset(buff, 0, sizeof(buff));

    if (!dns_dnequal(dn, rr.dnsrr_dn)) continue;
    if ((dlc->query_ctype == DNS_C_ANY || dlc->query_ctype == rr.dnsrr_cls) &&
        (dlc->query_rtype == DNS_T_ANY || dlc->query_rtype == rr.dnsrr_typ)) {
      lua_newtable(L);
      lua_pushinteger(L, rr.dnsrr_ttl);
      lua_setfield(L, -2, "ttl");

      switch(rr.dnsrr_typ) {
        case DNS_T_A:
          if(rr.dnsrr_dsz == 4) {
            snprintf(buff, sizeof(buff), "%d.%d.%d.%d",
                     dptr[0], dptr[1], dptr[2], dptr[3]);
            lua_pushstring(L, buff);
            lua_setfield(L, -2, "a");
          }
          break;

        case DNS_T_AAAA:
          if(rr.dnsrr_dsz == 16) {
            inet_ntop(AF_INET6, dptr, buff, 16);
            lua_pushstring(L, buff);
            lua_setfield(L, -2, "aaaa");
          }
          break;

        case DNS_T_TXT:
          totalsize = 0;
          for(tmp = dptr; tmp < dend; totalsize += *tmp, tmp += *tmp + 1)
            if(tmp + *tmp + 1 > dend) break;
          /* worst case: every character escaped + '\0' */
          txt_str = alloca(totalsize * 3 + 1);
          if(!txt_str) break;
          c = txt_str;
          for(tmp = dptr; tmp < dend; tmp += *tmp + 1)
            c = encode_txt(c, tmp+1, *tmp);
          lua_pushstring(L, txt_str);
          lua_setfield(L, -2, "txt");
          break;

        case DNS_T_MX:
          lua_pushinteger(L, dns_get16(dptr));
          lua_setfield(L, -2, "preference");
          tmp = dptr + 2;
          if(dns_getdn(pkt, &tmp, end, dn, DNS_MAXDN) <= 0 || tmp != dend)
            break;
          dns_dntop(dn, buff + strlen(buff), sizeof(buff) - strlen(buff));
          lua_pushstring(L, buff);
          lua_setfield(L, -2, "mx");
          break;

        case DNS_T_CNAME: if(!fieldname) fieldname = "cname";
        case DNS_T_PTR: if(!fieldname) fieldname = "ptr";
        case DNS_T_NS: if(!fieldname) fieldname = "ns";
        case DNS_T_MB: if(!fieldname) fieldname = "mb";
        case DNS_T_MD: if(!fieldname) fieldname = "md";
        case DNS_T_MF: if(!fieldname) fieldname = "mf";
        case DNS_T_MG: if(!fieldname) fieldname = "mg";
        case DNS_T_MR: if(!fieldname) fieldname = "mr";
         if(dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN) <= 0) break;
         dns_dntop(dn, buff, sizeof(buff));
         lua_pushstring(L, buff);
         lua_setfield(L, -2, fieldname);
         break;

        default:
          break;
      }
      ++nrr;
    }
    else if (rr.dnsrr_typ == DNS_T_CNAME && !nrr) {
      if (dns_getdn(pkt, &rr.dnsrr_dptr, end,
                    p.dnsp_dnbuf, sizeof(p.dnsp_dnbuf)) <= 0 ||
          rr.dnsrr_dptr != rr.dnsrr_dend) {
        break;
      }
    }
  }

 cleanup:
  if(result) free(result);
  if(dlc->active) dlc->ci->lmc->resume(dlc->ci, nrr);
  lookup_ctx_release(dlc);
}
Пример #3
0
LUALIB_API int luaopen_zlib(lua_State *L)
{
    const luaL_reg lzstream_meta[] =
    {
        {"write",           lzstream_compress   },
        {"read",            lzstream_decompress },
        {"lines",           lzstream_lines      },
        {"flush",           lzstream_flush      },
        {"close",           lzstream_close      },

        {"adler",           lzstream_adler      },

        {"__tostring",      lzstream_tostring   },
        {"__gc",            lzstream_gc         },
        {NULL, NULL}
    };

    const luaL_reg zlib[] =
    {
        {"version",         lzlib_version       },
        {"adler32",         lzlib_adler32       },
        {"crc32",           lzlib_crc32         },

        {"deflate",         lzlib_deflate       },
        {"inflate",         lzlib_inflate       },

        {"compress",        lzlib_compress      },
        {"decompress",      lzlib_decompress    },

        {NULL, NULL}
    };

    /* ====================================================================== */

    /* create new metatable for zlib compression structures */
    luaL_newmetatable(L, ZSTREAMMETA);
    lua_pushliteral(L, "__index");
    lua_pushvalue(L, -2);               /* push metatable */
    lua_rawset(L, -3);                  /* metatable.__index = metatable */

    /*
    ** Stack: metatable
    */
    luaL_register(L, NULL, lzstream_meta);

    lua_pop(L, 1);                      /* remove metatable from stack */

    /*
    ** Stack:
    */
    lua_newtable(L);

    lua_pushliteral (L, "_COPYRIGHT");
    lua_pushliteral (L, "Copyright (C) 2003-2008 Tiago Dionizio");
    lua_settable (L, -3);
    lua_pushliteral (L, "_DESCRIPTION");
    lua_pushliteral (L, "Lua 5 interface to access zlib library functions");
    lua_settable (L, -3);
    lua_pushliteral (L, "_VERSION");
    lua_pushliteral (L, "lzlib 0.4-work2");
    lua_settable (L, -3);

    luaL_register(L, NULL, zlib);

    /*
    ** Stack: zlib table
    */
    return 1;
}
Пример #4
0
int luaopen_myecho(lua_State *L)
    {
    lua_newtable(L); 
    luaL_setfuncs(L, Functions, 0);
    return 1;
    }
Пример #5
0
int process(lua_State *L, const char *name, const char* filter_name, int list_only) {
    struct archive *a = archive_read_new();
    archive_read_support_filter_all(a);
    archive_read_support_format_all(a);
    if ( (archive_read_open_filename(a, name, 10240)) ) {
        lua_pushnil(L);
        lua_pushfstring(L, "Error: can't read archive %s: %s\n", name, archive_error_string(a));
        return 2;
    }

    lua_newtable(L);
    int top = lua_gettop(L);
    struct archive_entry *entry;
    int r;
    int total = 0;
    for (;;) {
        r = archive_read_next_header(a, &entry);
        if (r == ARCHIVE_EOF)
            break;

        if (r != ARCHIVE_OK) {
            lua_pushnil(L);
            lua_pushfstring(L, "%s\n", archive_error_string(a));
            aclose(a);
            return 2;
        }

        if (r < ARCHIVE_WARN) {
            lua_pushnil(L);
            lua_pushfstring(L, "%s\n", "Warning from archive");
            aclose(a);
            return 2;
        }

        // skip dirs
        if (!S_ISREG(archive_entry_mode(entry)))
            continue;

        const char *name = archive_entry_pathname(entry);
        if(list_only) {
            lua_pushstring(L, name);
            lua_rawseti(L, top, ++total);
            archive_read_data_skip(a); // automatically called anyway
            continue;
        }

        if ( filter_name
                && ! ( strlen(filter_name)==strlen(name) && strncmp(filter_name, name, strlen(name))==0 ) )
        {
            archive_read_data_skip(a); // automatically called anyway
            continue;
        }

        size_t entry_size = archive_entry_size(entry);
        if (entry_size > 0) {
            char buff[entry_size];
            ssize_t size = archive_read_data(a, buff, entry_size);
            if(size <= 0) {
                //TODO: send a warning or a black image
                //lua_pushfstring(L, "Corrupted data: %s\n", name);
                //lua_error(L);
            }
            lua_pushlstring(L, buff, entry_size);
            if(filter_name)
                lua_rawseti(L, top, 1);
            else
                lua_setfield(L, top, name);
        }
        if(filter_name)break;
    }
    aclose(a);
    return 1;
}
Пример #6
0
int heka_decode_message(lua_State *lua)
{
  int n = lua_gettop(lua);
  if (n != 1 || lua_type(lua, 1) != LUA_TSTRING) {
    return luaL_argerror(lua, 0, "must have one string argument");
  }

  size_t len;
  const char *pbstr = lua_tolstring(lua, 1, &len);
  if (len < 20) {
    return luaL_error(lua, "invalid message, too short");
  }

  const char *p = pbstr;
  const char *lp = p;
  const char *e = pbstr + len;
  int wiretype = 0;
  int tag = 0;
  int has_uuid = 0;
  int has_timestamp = 0;
  int field_count = 0;

  lua_newtable(lua); // message table index 2
  do {
    p = lsb_pb_read_key(p, &tag, &wiretype);

    switch (tag) {
    case 1:
      p = read_string(lua, wiretype, p, e);
      if (p && p - lp == 18) {
        lua_setfield(lua, 2, "Uuid");
        has_uuid = 1;
      } else {
        p = NULL;
      }
      break;

    case 2:
      p = process_varint(lua, "Timestamp", wiretype, 2, p, e);
      if (p) {
        has_timestamp = 1;
      }
      break;

    case 3:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 2, "Type");
      }
      break;

    case 4:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 2, "Logger");
      }
      break;

    case 5:
      p = process_varint(lua, "Severity", wiretype, 2, p, e);
      break;

    case 6:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 2, "Payload");
      }
      break;

    case 7:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 2, "EnvVersion");
      }
      break;

    case 8:
      p = process_varint(lua, "Pid", wiretype, 2, p, e);
      break;

    case 9:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 2, "Hostname");
      }
      break;

    case 10:
      if (wiretype != 2) {
        p = NULL;
        break;
      }
      if (field_count == 0) {
        lua_newtable(lua); // Fields table index 3
      }
      p = process_fields(lua, p, e);
      if (p) {
        lua_rawseti(lua, 3, ++field_count);
      }
      break;

    default:
      p = NULL; // don't allow unknown tags
      break;
    }
    if (p) lp = p;
  } while (p && p < e);

  if (!p) {
    return luaL_error(lua, "error in tag: %d wiretype: %d offset: %d", tag,
                      wiretype, (const char *)lp - pbstr);
  }

  if (!has_uuid || !has_timestamp) {
    return luaL_error(lua, "missing required field uuid: %s timestamp: %s",
                      has_uuid ? "found" : "not found",
                      has_timestamp ? "found" : "not found");
  }

  if (field_count) {
    lua_setfield(lua, 2, "Fields");
  }

  return 1;
}
Пример #7
0
void luaopen_variables( lua_State *L )
{
    lua_newtable( L );
    luaL_register( L, NULL, vlclua_var_reg );
    lua_setfield( L, -2, "var" );
}
Пример #8
0
static gint
lua_util_tokenize_text (lua_State *L)
{
    const gchar *in = NULL;
    gsize len, pos, ex_len, i;
    GList *exceptions = NULL, *cur;
    struct rspamd_lua_text *t;
    struct process_exception *ex;
    GArray *res;
    rspamd_fstring_t *w;
    gboolean compat = FALSE, check_sig = FALSE;

    if (lua_type (L, 1) == LUA_TSTRING) {
        in = luaL_checklstring (L, 1, &len);
    }
    else if (lua_type (L, 1) == LUA_TTABLE) {
        t = lua_check_text (L, 1);

        if (t) {
            in = t->start;
            len = t->len;
        }
    }

    if (in == NULL) {
        lua_pushnil (L);
        return 1;
    }

    if (lua_gettop (L) > 1 && lua_type (L, 2) == LUA_TTABLE) {
        lua_pushvalue (L, 2);
        lua_pushnil (L);

        while (lua_next (L, -2) != 0) {
            if (lua_type (L, -1) == LUA_TTABLE) {
                lua_rawgeti (L, -1, 1);
                pos = luaL_checknumber (L, -1);
                lua_pop (L, 1);
                lua_rawgeti (L, -1, 2);
                ex_len = luaL_checknumber (L, -1);
                lua_pop (L, 1);

                if (ex_len > 0) {
                    ex = g_slice_alloc (sizeof (*ex));
                    ex->pos = pos;
                    ex->len = ex_len;
                    exceptions = g_list_prepend (exceptions, ex);
                }
            }
            lua_pop (L, 1);
        }

        lua_pop (L, 1);
    }

    if (lua_gettop (L) > 2 && lua_type (L, 3) == LUA_TBOOLEAN) {
        compat = lua_toboolean (L, 3);
    }

    if (lua_gettop (L) > 3 && lua_type (L, 4) == LUA_TBOOLEAN) {
        check_sig = lua_toboolean (L, 4);
    }

    if (exceptions) {
        exceptions = g_list_reverse (exceptions);
    }

    res = rspamd_tokenize_text ((gchar *)in, len, TRUE, 0, exceptions, compat,
                                check_sig);

    if (res == NULL) {
        lua_pushnil (L);
    }
    else {
        lua_newtable (L);

        for (i = 0; i < res->len; i ++) {
            w = &g_array_index (res, rspamd_fstring_t, i);
            lua_pushlstring (L, w->begin, w->len);
            lua_rawseti (L, -2, i + 1);
        }
    }

    cur = exceptions;
    while (cur) {
        ex = cur->data;
        g_slice_free1 (sizeof (*ex), ex);
        cur = g_list_next (cur);
    }

    g_list_free (exceptions);

    return 1;
}
Пример #9
0
 void push_keyboard_constants(lua_State* L)
 {
     lua_newtable(L);
     KB_AUTO(Unknown);
     KB_AUTO(Space);
     KB_AUTO(Apostrophe);
     KB_AUTO(Comma);
     KB_AUTO(Minus);
     KB_AUTO(Period);
     KB_AUTO(Slash);
     KB_AUTO(Num0);
     KB_AUTO(Num1);
     KB_AUTO(Num2);
     KB_AUTO(Num3);
     KB_AUTO(Num4);
     KB_AUTO(Num5);
     KB_AUTO(Num6);
     KB_AUTO(Num7);
     KB_AUTO(Num8);
     KB_AUTO(Num9);
     KB_AUTO(Semicolon);
     KB_AUTO(Equal);
     KB_AUTO(A);
     KB_AUTO(B);
     KB_AUTO(C);
     KB_AUTO(D);
     KB_AUTO(E);
     KB_AUTO(F);
     KB_AUTO(G);
     KB_AUTO(H);
     KB_AUTO(I);
     KB_AUTO(J);
     KB_AUTO(K);
     KB_AUTO(L);
     KB_AUTO(M);
     KB_AUTO(N);
     KB_AUTO(O);
     KB_AUTO(P);
     KB_AUTO(Q);
     KB_AUTO(R);
     KB_AUTO(S);
     KB_AUTO(T);
     KB_AUTO(U);
     KB_AUTO(V);
     KB_AUTO(W);
     KB_AUTO(X);
     KB_AUTO(Y);
     KB_AUTO(Z);
     KB_AUTO(LeftBracket);
     KB_AUTO(Backslash);
     KB_AUTO(RightBracket);
     KB_AUTO(Tilde);
     KB_AUTO(World1);
     KB_AUTO(World2);
     KB_AUTO(Escape);
     KB_AUTO(Enter);
     KB_AUTO(Tab);
     KB_AUTO(Backspace);
     KB_AUTO(Insert);
     KB_AUTO(Delete);
     KB_AUTO(Right);
     KB_AUTO(Left);
     KB_AUTO(Down);
     KB_AUTO(Up);
     KB_AUTO(PageUp);
     KB_AUTO(PageDown);
     KB_AUTO(Home);
     KB_AUTO(End);
     KB_AUTO(CapsLock);
     KB_AUTO(ScrollLock);
     KB_AUTO(NumLock);
     KB_AUTO(PrintScreen);
     KB_AUTO(Pause);
     KB_AUTO(F1);
     KB_AUTO(F2);
     KB_AUTO(F3);
     KB_AUTO(F4);
     KB_AUTO(F5);
     KB_AUTO(F6);
     KB_AUTO(F7);
     KB_AUTO(F8);
     KB_AUTO(F9);
     KB_AUTO(F10);
     KB_AUTO(F11);
     KB_AUTO(F12);
     KB_AUTO(F13);
     KB_AUTO(F14);
     KB_AUTO(F15);
     KB_AUTO(F16);
     KB_AUTO(F17);
     KB_AUTO(F18);
     KB_AUTO(F19);
     KB_AUTO(F20);
     KB_AUTO(F21);
     KB_AUTO(F22);
     KB_AUTO(F23);
     KB_AUTO(F24);
     KB_AUTO(F25);
     KB_AUTO(KP0);
     KB_AUTO(KP0);
     KB_AUTO(KP0);
     KB_AUTO(KP1);
     KB_AUTO(KP2);
     KB_AUTO(KP3);
     KB_AUTO(KP4);
     KB_AUTO(KP5);
     KB_AUTO(KP6);
     KB_AUTO(KP7);
     KB_AUTO(KP8);
     KB_AUTO(KP9);
     KB_AUTO(KPDecimal);
     KB_AUTO(KPDivide);
     KB_AUTO(KPMultiply);
     KB_AUTO(KPSubtract);
     KB_AUTO(KPAdd);
     KB_AUTO(KPEnter);
     KB_AUTO(LeftShift);
     KB_AUTO(LeftControl);
     KB_AUTO(LeftAlt);
     KB_AUTO(LeftSuper);
     KB_AUTO(RightShift);
     KB_AUTO(RightControl);
     KB_AUTO(RightAlt);
     KB_AUTO(RightSuper);
     KB_AUTO(Menu);
 }
Пример #10
0
int dt_lua_init_call(lua_State *L) {
  lua_newtable(L);
  lua_setfield(darktable.lua_state,LUA_REGISTRYINDEX,"dt_lua_delayed_events");
  return 0;
}
Пример #11
0
void ScriptUtil::registerClass(const char* name, const luaL_Reg* members, lua_CFunction newFunction, 
    lua_CFunction deleteFunction, const luaL_Reg* statics,  const std::vector<std::string>& scopePath)
{
    ScriptController* sc = Game::getInstance()->getScriptController();

    // If the type is an inner type, get the correct parent 
    // table on the stack before creating the table for the class.
    if (!scopePath.empty())
    {
        std::string tablename = name;

        // Strip off the scope path part of the name.
        lua_getglobal(sc->_lua, scopePath[0].c_str());
        std::size_t index = tablename.find(scopePath[0]);
        if (index != std::string::npos)
            tablename = tablename.substr(index + scopePath[0].size());
        
        for (unsigned int i = 1; i < scopePath.size(); i++)
        {
            lua_pushstring(sc->_lua, scopePath[i].c_str());
            lua_gettable(sc->_lua, -2);

            index = tablename.find(scopePath[i]);
            if (index != std::string::npos)
                tablename = tablename.substr(index + scopePath[i].size());
        }

        lua_pushstring(sc->_lua, tablename.c_str());
        lua_newtable(sc->_lua);
    }
    else
    {
        // If the type is not an inner type, set it as a global table.
        lua_newtable(sc->_lua);
        lua_pushvalue(sc->_lua, -1);
        lua_setglobal(sc->_lua, name);
    }
    
    // Create the metatable and populate it with the member functions.
    lua_pushliteral(sc->_lua, "__metatable");
    luaL_newmetatable(sc->_lua, name);
    if (members)
        luaL_setfuncs(sc->_lua, members, 0);
    lua_pushstring(sc->_lua, "__index");
    lua_pushvalue(sc->_lua, -2);
    lua_settable(sc->_lua, -3);

    // Add the delete function if it was specified.
    if (deleteFunction)
    {
        lua_pushstring(sc->_lua, "__gc");
        lua_pushcfunction(sc->_lua, deleteFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the metatable on the main table.
    lua_settable(sc->_lua, -3);
    
    // Populate the main table with the static functions.
    if (statics)
        luaL_setfuncs(sc->_lua, statics, 0);

    // Set the new function(s) for the class.
    if (newFunction)
    {
        lua_pushliteral(sc->_lua, "new");
        lua_pushcfunction(sc->_lua, newFunction);
        lua_settable(sc->_lua, -3);
    }

    // Set the table we just created within the correct parent table.
    if (!scopePath.empty())
    {
        lua_settable(sc->_lua, -3);

        // Pop all the parent tables off the stack.
        int size = scopePath.size();
        lua_pop(sc->_lua, size);
    }
    else
    {
        // Pop the main table off the stack.
        lua_pop(sc->_lua, 1);
    }
}
Пример #12
0
int luaC_mean_energies(lua_State *L)
{
  const FluidEquations &fluid    = *HydroModule::Mara->fluid;
  const EquationOfState &eos     = *HydroModule::Mara->eos;
  const int Nq                   =  HydroModule::Mara->domain->get_Nq();
  const std::valarray<double> &P =  HydroModule::Mara->PrimitiveArray;

  double kinetic  = 0.0;
  double internal = 0.0;
  double magnetic = 0.0;
  double total    = 0.0;

  for (size_t m=0; m<P.size(); m+=Nq) {
    if (absolute_index_is_ghost(m/Nq)) continue;

    const std::slice M(m, Nq, 1);
    const std::valarray<double> P0 = P[M];
    double *U0 = new double[Nq];

    fluid.PrimToCons(&P0[0], &U0[0]);

    const double v2 = P0[vx]*P0[vx] + P0[vy]*P0[vy] + P0[vz]*P0[vz];
    const double T0 = eos.Temperature_p(P0[rho], P0[pre]);
    const double u0 = eos.Internal(P0[rho], T0);

    if (typeid(fluid) == typeid(AdiabaticIdealSrhd) ||
        typeid(fluid) == typeid(AdiabaticIdealRmhd)) {

      const double rhoh = P0[rho] + u0 + P0[pre];
      const double W0   = 1.0 / sqrt(1.0 - v2);
      const double e_f  = rhoh * W0*W0 - P0[pre] - U0[ddd];
      const double e_m  = U0[tau] - e_f;

      magnetic += e_m;
      kinetic  += P0[rho] * W0 * (W0-1);
      internal += W0 * u0;
      total    += U0[tau];
    }
    else if (typeid(fluid) == typeid(AdiabaticIdealEulers)) {

      magnetic += 0.0;
      kinetic  += 0.5 * P0[rho] * v2;
      internal += u0;
      total    += U0[tau];
    }
    delete [] U0;
  }

  magnetic = Mara_mpi_dbl_sum(magnetic) / TTL_ZONES;
  kinetic  = Mara_mpi_dbl_sum(kinetic ) / TTL_ZONES;
  internal = Mara_mpi_dbl_sum(internal) / TTL_ZONES;
  total    = Mara_mpi_dbl_sum(total   ) / TTL_ZONES;

  lua_newtable(L);
  lua_pushstring(L, "magnetic"); lua_pushnumber(L, magnetic); lua_settable(L, -3);
  lua_pushstring(L, "kinetic");  lua_pushnumber(L, kinetic);  lua_settable(L, -3);
  lua_pushstring(L, "internal"); lua_pushnumber(L, internal); lua_settable(L, -3);
  lua_pushstring(L, "total");    lua_pushnumber(L, total);    lua_settable(L, -3);

  return 1;
}
Пример #13
0
// get_mapgen_object(objectname)
// returns the requested object used during map generation
int ModApiMapgen::l_get_mapgen_object(lua_State *L)
{
	NO_MAP_LOCK_REQUIRED;

	const char *mgobjstr = lua_tostring(L, 1);

	int mgobjint;
	if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
		return 0;

	enum MapgenObject mgobj = (MapgenObject)mgobjint;

	EmergeManager *emerge = getServer(L)->getEmergeManager();
	Mapgen *mg = emerge->getCurrentMapgen();
	if (!mg)
		throw LuaError("Must only be called in a mapgen thread!");

	size_t maplen = mg->csize.X * mg->csize.Z;

	switch (mgobj) {
	case MGOBJ_VMANIP: {
		MMVManip *vm = mg->vm;

		// VoxelManip object
		LuaVoxelManip *o = new LuaVoxelManip(vm, true);
		*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
		luaL_getmetatable(L, "VoxelManip");
		lua_setmetatable(L, -2);

		// emerged min pos
		push_v3s16(L, vm->m_area.MinEdge);

		// emerged max pos
		push_v3s16(L, vm->m_area.MaxEdge);

		return 3;
	}
	case MGOBJ_HEIGHTMAP: {
		if (!mg->heightmap)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->heightmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_BIOMEMAP: {
		if (!mg->biomegen)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->biomegen->biomemap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_HEATMAP: {
		if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
			return 0;

		BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushnumber(L, bg->heatmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}

	case MGOBJ_HUMIDMAP: {
		if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
			return 0;

		BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushnumber(L, bg->humidmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_GENNOTIFY: {
		std::map<std::string, std::vector<v3s16> >event_map;
		std::map<std::string, std::vector<v3s16> >::iterator it;

		mg->gennotify.getEvents(event_map);

		lua_newtable(L);
		for (it = event_map.begin(); it != event_map.end(); ++it) {
			lua_newtable(L);

			for (size_t j = 0; j != it->second.size(); j++) {
				push_v3s16(L, it->second[j]);
				lua_rawseti(L, -2, j + 1);
			}

			lua_setfield(L, -2, it->first.c_str());
		}

		return 1;
	}
	}

	return 0;
}
Пример #14
0
Файл: lem.c Проект: esmil/lem
int
main(int argc, char *argv[])
{
#if EV_MULTIPLICITY
	lem_loop = ev_default_loop(LEM_LOOPFLAGS);
	if (lem_loop == NULL) {
#else
	if (!ev_default_loop(LEM_LOOPFLAGS)) {
#endif
		lem_log_error("lem: error initializing event loop");
		return EXIT_FAILURE;
	}

	if (setsignal(SIGPIPE, SIG_IGN, 0)
#if !EV_CHILD_ENABLE
	    || setsignal(SIGCHLD, SIG_DFL, SA_NOCLDSTOP | SA_NOCLDWAIT)
#endif
	   )
		goto error;

	/* create main Lua state */
	L = luaL_newstate();
	if (L == NULL) {
		lem_log_error("lem: error initializing Lua state");
		goto error;
	}
	luaL_openlibs(L);

	/* push thread table */
	lua_newtable(L);

	/* initialize runqueue */
	runqueue_wait_init();
	ev_idle_start(LEM_ &rq.w);
	rq.queue = lem_xmalloc(LEM_INITIAL_QUEUESIZE
			* sizeof(struct lem_runqueue_slot));
	rq.first = rq.last = 0;
	rq.mask = LEM_INITIAL_QUEUESIZE - 1;

	/* initialize threadpool */
	if (pool_init()) {
		lem_log_error("lem: error initializing threadpool");
		goto error;
	}

	/* load file */
	if (queue_file(argc, argv, 1))
		goto error;

	/* start the mainloop */
	ev_loop(LEM_ 0);
	lem_debug("event loop exited");

	/* if there is an error message left on L print it */
	if (lua_type(L, -1) == LUA_TSTRING)
		lem_log_error("lem: %s", lua_tostring(L, -1));

	/* shutdown Lua */
	lua_close(L);

	/* free runqueue */
	free(rq.queue);

	/* destroy loop */
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	lem_debug("Bye %s", exit_status == EXIT_SUCCESS ? "o/" : ":(");
	return exit_status;

error:
	if (L)
		lua_close(L);
	if (rq.queue)
		free(rq.queue);
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	return EXIT_FAILURE;
}
Пример #15
0
int cache_parse_lua(server *srv, connection *con, plugin_data *p, buffer *fn) {
	lua_State *L;
	readme rm;
	int ret = -1;
	buffer *b = buffer_init();
	int header_tbl = 0;

	rm.done = 0;
	stream_open(&rm.st, fn);

	/* push the lua file to the interpreter and see what happends */
	L = luaL_newstate();
	luaL_openlibs(L);

	/* register functions */
	lua_register(L, "md5", f_crypto_md5);
	lua_register(L, "file_mtime", f_file_mtime);
	lua_register(L, "file_isreg", f_file_isreg);
	lua_register(L, "file_isdir", f_file_isreg);
	lua_register(L, "dir_files", f_dir_files);

#ifdef HAVE_MEMCACHE_H
	lua_pushliteral(L, "memcache_get_long");
	lua_pushlightuserdata(L, p->conf.mc);
	lua_pushcclosure(L, f_memcache_get_long, 1);
	lua_settable(L, LUA_GLOBALSINDEX);

	lua_pushliteral(L, "memcache_get_string");
	lua_pushlightuserdata(L, p->conf.mc);
	lua_pushcclosure(L, f_memcache_get_string, 1);
	lua_settable(L, LUA_GLOBALSINDEX);

	lua_pushliteral(L, "memcache_exists");
	lua_pushlightuserdata(L, p->conf.mc);
	lua_pushcclosure(L, f_memcache_exists, 1);
	lua_settable(L, LUA_GLOBALSINDEX);
#endif
	/* register CGI environment */
	lua_pushliteral(L, "request");
	lua_newtable(L);
	lua_settable(L, LUA_GLOBALSINDEX);

	lua_pushliteral(L, "request");
	header_tbl = lua_gettop(L);
	lua_gettable(L, LUA_GLOBALSINDEX);

	c_to_lua_push(L, header_tbl, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
	c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
	c_to_lua_push(L, header_tbl, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path));
	c_to_lua_push(L, header_tbl, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root));
	if (!buffer_is_empty(con->request.pathinfo)) {
		c_to_lua_push(L, header_tbl, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
	}

	c_to_lua_push(L, header_tbl, CONST_STR_LEN("CWD"), CONST_BUF_LEN(p->basedir));
	c_to_lua_push(L, header_tbl, CONST_STR_LEN("BASEURL"), CONST_BUF_LEN(p->baseurl));

	/* register GET parameter */
	lua_pushliteral(L, "get");
	lua_newtable(L);
	lua_settable(L, LUA_GLOBALSINDEX);

	lua_pushliteral(L, "get");
	header_tbl = lua_gettop(L);
	lua_gettable(L, LUA_GLOBALSINDEX);

	buffer_copy_string_buffer(b, con->uri.query);
	cache_export_get_params(L, header_tbl, b);
	buffer_reset(b);

	/* 2 default constants */
	lua_pushliteral(L, "CACHE_HIT");
	lua_pushnumber(L, 0);
	lua_settable(L, LUA_GLOBALSINDEX);

	lua_pushliteral(L, "CACHE_MISS");
	lua_pushnumber(L, 1);
	lua_settable(L, LUA_GLOBALSINDEX);

	/* load lua program */
	if (lua_load(L, load_file, &rm, fn->ptr) || lua_pcall(L,0,1,0)) {
		log_error_write(srv, __FILE__, __LINE__, "s",
				lua_tostring(L,-1));

		goto error;
	}

	/* get return value */
	ret = (int)lua_tonumber(L, -1);
	lua_pop(L, 1);

	/* fetch the data from lua */
	lua_to_c_get_string(L, "trigger_handler", p->trigger_handler);

	if (0 == lua_to_c_get_string(L, "output_contenttype", b)) {
		response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(b));
	}

	if (ret == 0) {
		/* up to now it is a cache-hit, check if all files exist */

		int curelem;
		time_t mtime = 0;

		if (!lua_to_c_is_table(L, "output_include")) {
			log_error_write(srv, __FILE__, __LINE__, "s",
				"output_include is missing or not a table");
			ret = -1;

			goto error;
		}

		lua_pushstring(L, "output_include");

		curelem = lua_gettop(L);
		lua_gettable(L, LUA_GLOBALSINDEX);

		/* HOW-TO build a etag ?
		 * as we don't just have one file we have to take the stat()
		 * from all base files, merge them and build the etag from
		 * it later.
		 *
		 * The mtime of the content is the mtime of the freshest base file
		 *
		 * */

		lua_pushnil(L);  /* first key */
		while (lua_next(L, curelem) != 0) {
			stat_cache_entry *sce = NULL;
			/* key' is at index -2 and value' at index -1 */

			if (lua_isstring(L, -1)) {
				const char *s = lua_tostring(L, -1);

				/* the file is relative, make it absolute */
				if (s[0] != '/') {
					buffer_copy_string_buffer(b, p->basedir);
					buffer_append_string(b, lua_tostring(L, -1));
				} else {
					buffer_copy_string(b, lua_tostring(L, -1));
				}

				if (HANDLER_ERROR == stat_cache_get_entry(srv, con, b, &sce)) {
					/* stat failed */

					switch(errno) {
					case ENOENT:
						/* a file is missing, call the handler to generate it */
						if (!buffer_is_empty(p->trigger_handler)) {
							ret = 1; /* cache-miss */

							log_error_write(srv, __FILE__, __LINE__, "s",
									"a file is missing, calling handler");

							break;
						} else {
							/* handler not set -> 500 */
							ret = -1;

							log_error_write(srv, __FILE__, __LINE__, "s",
									"a file missing and no handler set");

							break;
						}
						break;
					default:
						break;
					}
				} else {
					chunkqueue_append_file(con->write_queue, b, 0, sce->st.st_size);
					if (sce->st.st_mtime > mtime) mtime = sce->st.st_mtime;
				}
			} else {
				/* not a string */
				ret = -1;
				log_error_write(srv, __FILE__, __LINE__, "s",
						"not a string");
				break;
			}

			lua_pop(L, 1);  /* removes value'; keeps key' for next iteration */
		}

		lua_settop(L, curelem - 1);

		if (ret == 0) {
			data_string *ds;
			char timebuf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")];
			buffer tbuf;

			con->file_finished = 1;

			ds = (data_string *)array_get_element(con->response.headers, "Last-Modified");

			/* no Last-Modified specified */
			if ((mtime) && (NULL == ds)) {

				strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime));

				response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), timebuf, sizeof(timebuf) - 1);


				tbuf.ptr = timebuf;
				tbuf.used = sizeof(timebuf);
				tbuf.size = sizeof(timebuf);
			} else if (ds) {
				tbuf.ptr = ds->value->ptr;
				tbuf.used = ds->value->used;
				tbuf.size = ds->value->size;
			} else {
				tbuf.size = 0;
				tbuf.used = 0;
				tbuf.ptr = NULL;
			}

			if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, &tbuf, con->physical.etag)) {
				/* ok, the client already has our content,
				 * no need to send it again */

				chunkqueue_reset(con->write_queue);
				ret = 0; /* cache-hit */
			}
		} else {
			chunkqueue_reset(con->write_queue);
		}
	}

	if (ret == 1 && !buffer_is_empty(p->trigger_handler)) {
		/* cache-miss */
		buffer_copy_string_buffer(con->uri.path, p->baseurl);
		buffer_append_string_buffer(con->uri.path, p->trigger_handler);

		buffer_copy_string_buffer(con->physical.path, p->basedir);
		buffer_append_string_buffer(con->physical.path, p->trigger_handler);

		chunkqueue_reset(con->write_queue);
	}

error:
	lua_close(L);

	stream_close(&rm.st);
	buffer_free(b);

	return ret /* cache-error */;
}
Пример #16
0
TOLUA_API void tolua_open (lua_State* L)
{
    int top = lua_gettop(L);
    lua_pushstring(L,"tolua_opened");
    lua_rawget(L,LUA_REGISTRYINDEX);
    if (!lua_isboolean(L,-1))
    {
        lua_pushstring(L,"tolua_opened");
        lua_pushboolean(L,1);
        lua_rawset(L,LUA_REGISTRYINDEX);

#ifndef LUA_VERSION_NUM /* only prior to lua 5.1 */
        /* create peer object table */
        lua_pushstring(L, "tolua_peers");
        lua_newtable(L);
        /* make weak key metatable for peers indexed by userdata object */
        lua_newtable(L);
        lua_pushliteral(L, "__mode");
        lua_pushliteral(L, "k");
        lua_rawset(L, -3);                /* stack: string peers mt */
        lua_setmetatable(L, -2);   /* stack: string peers */
        lua_rawset(L,LUA_REGISTRYINDEX);
#endif

        /* create object ptr -> udata mapping table */
        lua_pushstring(L,"tolua_ubox");
        lua_newtable(L);
        /* make weak value metatable for ubox table to allow userdata to be
           garbage-collected */
        lua_newtable(L);
        lua_pushliteral(L, "__mode");
        lua_pushliteral(L, "v");
        lua_rawset(L, -3);               /* stack: string ubox mt */
        lua_setmetatable(L, -2);  /* stack: string ubox */
        lua_rawset(L,LUA_REGISTRYINDEX);
        
//        /* create object ptr -> class type mapping table */
//        lua_pushstring(L, "tolua_ptr2type");
//        lua_newtable(L);
//        lua_rawset(L, LUA_REGISTRYINDEX);

        lua_pushstring(L,"tolua_super");
        lua_newtable(L);
        lua_rawset(L,LUA_REGISTRYINDEX);
        lua_pushstring(L,"tolua_gc");
        lua_newtable(L);
        lua_rawset(L,LUA_REGISTRYINDEX);

        /* create gc_event closure */
        lua_pushstring(L, "tolua_gc_event");
        lua_pushstring(L, "tolua_gc");
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_pushstring(L, "tolua_super");
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_pushcclosure(L, class_gc_event, 2);
        lua_rawset(L, LUA_REGISTRYINDEX);

        tolua_newmetatable(L,"tolua_commonclass");

        tolua_module(L,NULL,0);
        tolua_beginmodule(L,NULL);
        tolua_module(L,"tolua",0);
        tolua_beginmodule(L,"tolua");
        tolua_function(L,"type",tolua_bnd_type);
        tolua_function(L,"takeownership",tolua_bnd_takeownership);
        tolua_function(L,"releaseownership",tolua_bnd_releaseownership);
        tolua_function(L,"cast",tolua_bnd_cast);
        tolua_function(L,"isnull",tolua_bnd_isnulluserdata);
        tolua_function(L,"inherit", tolua_bnd_inherit);
#ifdef LUA_VERSION_NUM /* lua 5.1 */
        tolua_function(L, "setpeer", tolua_bnd_setpeer);
        tolua_function(L, "getpeer", tolua_bnd_getpeer);
#endif

        tolua_endmodule(L);
        tolua_endmodule(L);
    }
    lua_settop(L,top);
}
Пример #17
0
void luaopen_volume( lua_State *L )
{
    lua_newtable( L );
    luaL_register( L, NULL, vlclua_volume_reg );
    lua_setfield( L, -2, "volume" );
}
Пример #18
0
int vm_hw_lua_cpu_disassemble(lua_State* L)
{
	vm_t* vm = vm_hw_lua_cpu_extract_cpu(L, 1);
	struct inst inst = vm_disassemble(vm, (uint16_t)luaL_checknumber(L, 2), true);
	lua_newtable(L);
	lua_newtable(L);
	lua_pushnumber(L, inst.original.full);
	lua_setfield(L, -2, "full");
	lua_pushnumber(L, inst.original.op);
	lua_setfield(L, -2, "op");
	lua_pushnumber(L, inst.original.a);
	lua_setfield(L, -2, "a");
	lua_pushnumber(L, inst.original.b);
	lua_setfield(L, -2, "b");
	lua_setfield(L, -2, "original");
	lua_newtable(L);
	if (inst.pretty.op != NULL)
		lua_pushstring(L, inst.pretty.op->data);
	else
		lua_pushnil(L);
	lua_setfield(L, -2, "op");
	if (inst.pretty.a != NULL)
		lua_pushstring(L, inst.pretty.a->data);
	else
		lua_pushnil(L);
	lua_setfield(L, -2, "a");
	if (inst.pretty.b != NULL)
		lua_pushstring(L, inst.pretty.b->data);
	else
		lua_pushnil(L);
	lua_setfield(L, -2, "b");
	lua_setfield(L, -2, "pretty");
	lua_pushnumber(L, inst.op);
	lua_setfield(L, -2, "op");
	lua_pushnumber(L, inst.a);
	lua_setfield(L, -2, "a");
	lua_pushnumber(L, inst.b);
	lua_setfield(L, -2, "b");
	lua_pushnumber(L, inst.size);
	lua_setfield(L, -2, "size");
	lua_newtable(L);
	if (inst.size >= 1)
	{
		lua_pushnumber(L, inst.extra[0]);
		lua_rawseti(L, -2, 1);
	}
	if (inst.size >= 2)
	{
		lua_pushnumber(L, inst.extra[1]);
		lua_rawseti(L, -2, 2);
	}
	lua_setfield(L, -2, "extra");
	lua_newtable(L);
	if (inst.used[0])
		lua_pushnumber(L, inst.next[0]);
	else
		lua_pushnil(L);
	lua_rawseti(L, -2, 1);
	if (inst.used[1])
		lua_pushnumber(L, inst.next[1]);
	else
		lua_pushnil(L);
	lua_rawseti(L, -2, 2);
	lua_setfield(L, -2, "next");
	bdestroy(inst.pretty.op);
	bdestroy(inst.pretty.a);
	bdestroy(inst.pretty.b);
	return 1;
}
Пример #19
0
static const char* process_fields(lua_State *lua, const char *p, const char *e)
{
  int tag = 0;
  int wiretype = 0;
  int has_name = 0;
  int value_count = 0;
  long long len = 0;

  p = lsb_pb_read_varint(p, e, &len);
  if (!p || len < 0 || p + len > e) {
    return NULL;
  }
  e = p + len; // only process to the end of the current field record

  lua_newtable(lua); // Table to be added to the Fields array index 4
  lua_newtable(lua); // Table to hold the value(s) index 5
  do {
    p = lsb_pb_read_key(p, &tag, &wiretype);

    switch (tag) {
    case 1:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 4, "name");
        has_name = 1;
      }
      break;

    case 2:
      p = process_varint(lua, "value_type", wiretype, 4, p, e);
      break;

    case 3:
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_setfield(lua, 4, "representation");
      }
      break;

    case 4: // value_string
    case 5: // value_bytes
      p = read_string(lua, wiretype, p, e);
      if (p) {
        lua_rawseti(lua, 5, ++value_count);
      }
      break;

    case 6: // value_integer
      {
        long long val = 0;
        switch (wiretype) {
        case 0:
          p = lsb_pb_read_varint(p, p + len, &val);
          if (!p) break;
          lua_pushnumber(lua, (lua_Number)val);
          lua_rawseti(lua, 5, ++value_count);
          break;
        case 2:
          p = lsb_pb_read_varint(p, e, &len);
          if (!p || len < 0 || p + len > e) {
            p = NULL;
            break;
          }
          do {
            p = lsb_pb_read_varint(p, p + len, &val);
            if (!p) break;
            lua_pushnumber(lua, (lua_Number)val);
            lua_rawseti(lua, 5, ++value_count);
          } while (p < e);
          break;
        default:
          p = NULL;
          break;
        }
      }
      break;

    case 7: // value_double
      {
        double val = 0;
        switch (wiretype) {
        case 1:
          if (p + sizeof(double) > e) {
            p = NULL;
            break;
          }
          memcpy(&val, p, sizeof(double));
          p += sizeof(double);
          lua_pushnumber(lua, val);
          lua_rawseti(lua, 5, ++value_count);
          break;
        case 2:
          p = lsb_pb_read_varint(p, e, &len);
          if (!p || len < 0 || p + len > e || len % sizeof(double) != 0) {
            p = NULL;
            break;
          }
          do {
            memcpy(&val, p, sizeof(double));
            p += sizeof(double);
            lua_pushnumber(lua, val);
            lua_rawseti(lua, 5, ++value_count);
          } while (p < e);
          break;
        default:
          p = NULL;
          break;
        }
      }
      break;

    case 8: // value_bool
      {
        long long val = 0;
        switch (wiretype) {
        case 0:
          p = lsb_pb_read_varint(p, p + len, &val);
          if (!p) break;
          lua_pushboolean(lua, (int)val);
          lua_rawseti(lua, 5, ++value_count);
          break;
        case 2:
          p = lsb_pb_read_varint(p, e, &len);
          if (!p || len < 0 || p + len > e) {
            p = NULL;
            break;
          }
          do {
            p = lsb_pb_read_varint(p, p + len, &val);
            if (!p) break;
            lua_pushboolean(lua, (int)val);
            lua_rawseti(lua, 5, ++value_count);
          } while (p < e);
          break;
        default:
          p = NULL;
          break;
        }
      }
      break;
    default:
      p = NULL; // don't allow unknown tags
      break;
    }
  } while (p && p < e);

  lua_setfield(lua, 4, "value");

  return has_name ? p : NULL;
}
Пример #20
0
void vm_hw_lua_cpu_push_cpu(lua_State* L, vm_t* vm)
{
	int cpu, cpu_mt, registers, registers_mt, ram, ram_mt, irq, irq_mt;

	// Create tables.
	lua_newtable(L);
	cpu = lua_gettop(L);
	lua_newtable(L);
	cpu_mt = lua_gettop(L);
	lua_newtable(L);
	registers = lua_gettop(L);
	lua_newtable(L);
	registers_mt = lua_gettop(L);
	lua_newtable(L);
	ram = lua_gettop(L);
	lua_newtable(L);
	ram_mt = lua_gettop(L);
	lua_newtable(L);
	irq = lua_gettop(L);
	lua_newtable(L);
	irq_mt = lua_gettop(L);

	// Push userdata into metatables.
	lua_pushlightuserdata(L, vm);
	lua_rawseti(L, cpu_mt, 0);
	lua_pushlightuserdata(L, vm);
	lua_rawseti(L, ram_mt, 0);
	lua_pushlightuserdata(L, vm);
	lua_rawseti(L, registers_mt, 0);
	lua_pushlightuserdata(L, vm);
	lua_rawseti(L, irq_mt, 0);

	// Create the metatable functions.
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_ram_get);
	lua_setfield(L, ram_mt, "__index");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_ram_set);
	lua_setfield(L, ram_mt, "__newindex");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_register_get);
	lua_setfield(L, registers_mt, "__index");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_register_set);
	lua_setfield(L, registers_mt, "__newindex");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_irq_get);
	lua_setfield(L, irq_mt, "__index");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_irq_set);
	lua_setfield(L, irq_mt, "__newindex");
	lua_pushcfunction(L, vm_hw_lua_cpu_handle_irq_length);
	lua_setfield(L, irq_mt, "__len");

	// Associate metatables.
	lua_pushvalue(L, cpu_mt);
	lua_setmetatable(L, cpu);
	lua_pushvalue(L, ram_mt);
	lua_setmetatable(L, ram);
	lua_pushvalue(L, irq_mt);
	lua_setmetatable(L, irq);
	lua_pushvalue(L, registers_mt);
	lua_setmetatable(L, registers);

	// FIXME: Protect the metatables.
	//lua_pushboolean(hw->state, true);
	//lua_setfield(hw->state, ram_mt, "__metatable");
	//lua_pushboolean(hw->state, true);
	//lua_setfield(hw->state, registers_mt, "__metatable");

	// Put ram and registers into CPU.
	lua_pushvalue(L, ram);
	lua_setfield(L, cpu, "ram");
	lua_pushvalue(L, registers);
	lua_setfield(L, cpu, "registers");
	lua_pushvalue(L, irq);
	lua_setfield(L, cpu, "irq");
	lua_pushcfunction(L, &vm_hw_lua_cpu_disassemble);
	lua_setfield(L, cpu, "disassemble");

	// Clean up stack.
	lua_pop(L, lua_gettop(L) - cpu);

	// CPU is now on top of the stack.
}
Пример #21
0
bool Script::syncTo(SafeArray<LuaType>* lt){

	#ifndef OLD_SYNC
		return true;
	#endif

	if(!doSync){
		return true;
	}

	if(lt==NULL){
		lt=&global;
	}


	for(int i=0; i<lt->size(); i++){

		if((*lt)[i].type==SCRIPT_TABLE){
			if((*lt)[i].newTable){
				lua_newtable(L); 
				(*lt)[i].newTable=false;
			}else{
				if(lt==&global){
					lua_pushstring(L, (*lt)[i].name.c_str());
					lua_gettable(L, LUA_GLOBALSINDEX); //get table[key] 
				}else{
					lua_pushstring(L, (*lt)[i].name.c_str());
					lua_gettable(L, -2); //get table[key] 
				}
			}

			if(!syncTo(&(*lt)[i].children)){
				return false;
			}

			if(lt==&global){
				lua_setglobal(L,(*lt)[i].name.c_str());
			}else{
				lua_pushstring(L, (*lt)[i].name.c_str());
				lua_insert(L, -2);
				lua_settable(L, -3);
			}
			
		}else if((*lt)[i].type==SCRIPT_TABLE_INT){

			if((*lt)[i].newTable){
				lua_newtable(L); 
				(*lt)[i].newTable=false;
			}else{
				if(lt==&global){

					console().write("error, numerical indices can't be for global tables");
					return false;
				}else{
					lua_pushnumber(L,(*lt)[i].nameint);
					lua_gettable(L, -2); //get table[key] 
				}
			}	
			
				if(!syncTo(&(*lt)[i].children)){
					return false;
				}

				if(lt==&global){
					console().write("error, numerical indices can't be for global tables");
					return false;
				}else{
					lua_pushnumber(L,(*lt)[i].nameint);
					lua_insert(L, -2);
					lua_settable(L, -3);
				}
			
		}else if((*lt)[i].type==SCRIPT_FLOAT){

			if(lt==&global){
				lua_pushnumber(L,(double)*(*lt)[i].value.f);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());

				float f=*(*lt)[i].value.f;

				lua_pushnumber(L,(double)*(*lt)[i].value.f);
				lua_settable(L, -3);
			}

		}else if((*lt)[i].type==SCRIPT_DOUBLE){
	
			if(lt==&global){
				lua_pushnumber(L,*(*lt)[i].value.d);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());
				lua_pushnumber(L,*(*lt)[i].value.d);
				lua_settable(L, -3);
			}

		}else if((*lt)[i].type==SCRIPT_INT){
	
			if(lt==&global){
				lua_pushnumber(L,(double)*(*lt)[i].value.i);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());

				float f=*(*lt)[i].value.i;

				lua_pushnumber(L,(double)*(*lt)[i].value.i);
				lua_settable(L, -3);
			}
		}else if((*lt)[i].type==SCRIPT_INT_STORED){
	
			if(lt==&global){
				lua_pushnumber(L,(double)(*lt)[i].value.is);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());

				lua_pushnumber(L,(double)(*lt)[i].value.is);
				lua_settable(L, -3);
			}
		}else if((*lt)[i].type==SCRIPT_BOOL){
			if(lt==&global){
				lua_pushboolean(L,*(*lt)[i].value.b);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());

				lua_pushboolean(L,*(*lt)[i].value.b);
				lua_settable(L, -3);
			}

		}else if((*lt)[i].type==SCRIPT_STRING){
			if(lt==&global){
				lua_pushstring(L,(*(*lt)[i].value.s).cStr());
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());

				lua_pushstring(L,(*(*lt)[i].value.s).cStr());
				lua_settable(L, -3);
			}
		}else if((*lt)[i].type==SCRIPT_FUNCTION){
			if(lt==&global){
				lua_pushcfunction(L, (*lt)[i].value.cfunc);
				lua_setglobal(L,(*lt)[i].name.cStr());
			}else{
				lua_pushstring(L, (*lt)[i].name.cStr());
				lua_pushcfunction(L, (*lt)[i].value.cfunc);

				lua_settable(L, -3);
			}

		}else{	
			console().write("Error: '"+(*lt)[i].name+"' when adding");
			return false;
		}
		
	}

	if(lt==&global){
		lua_settop(L, 0);
	}

	return true;
}
Пример #22
0
int main(int argc, char** argv)
{
	td_bin_allocator bin_alloc;
	const char *homedir;
	char exepath[512];
	int res, rc, i;
	lua_State* L;

	td_init_portable();

	if (0 != td_get_executable_path(exepath, sizeof exepath)) {
		fprintf(stderr, "couldn't find path to tundra executable");
		return 1;
	}

	if (NULL == (homedir = td_init_homedir())) {
		fprintf(stderr, "couldn't find tundra home dir");
		return 1;
	}

	td_bin_allocator_init(&bin_alloc);

	L = lua_newstate(td_lua_alloc, &bin_alloc);
	if (!L)
		exit(1);

	lua_atpanic(L, on_lua_panic);

	luaL_openlibs(L);

	tundra_open(L);

#if defined(TD_STANDALONE)
	/* this is equivalent to table.insert(package.loaders, 1, td_load_embedded_file) */

	/* get the function */
	lua_getglobal(L, "table");
	lua_getfield(L, -1, "insert");
	lua_remove(L, -2);
	assert(!lua_isnil(L, -1));

	/* arg1: the package.loaders table */
	lua_getglobal(L, "package");
	lua_getfield(L, -1, "loaders");
	lua_remove(L, -2);
	assert(!lua_isnil(L, -1));

	lua_pushinteger(L, 1); /* arg 2 */
	lua_pushcfunction(L, td_load_embedded_file); /* arg 3 */

	lua_call(L, 3, 0);
#endif

	/* setup package.path */
	{
		char ppath[1024];
		snprintf(ppath, sizeof(ppath),
			"%s" TD_PATHSEP_STR "scripts" TD_PATHSEP_STR "?.lua;"
			"%s" TD_PATHSEP_STR "lua" TD_PATHSEP_STR "etc" TD_PATHSEP_STR "?.lua", homedir, homedir);
		lua_getglobal(L, "package");
		assert(LUA_TTABLE == lua_type(L, -1));
		lua_pushstring(L, ppath);
		lua_setfield(L, -2, "path");
	}

	/* push our error handler on the stack now (before the chunk to run) */
	lua_pushcclosure(L, get_traceback, 0);

	switch (luaL_loadbuffer(L, boot_snippet, sizeof(boot_snippet)-1, "boot_snippet"))
	{
	case LUA_ERRMEM:
		td_croak("out of memory");
		return 1;
	case LUA_ERRSYNTAX:
		td_croak("syntax error\n%s\n", lua_tostring(L, -1));
		return 1;
	}

	lua_pushstring(L, homedir);

	lua_newtable(L);
	lua_pushstring(L, exepath);
	lua_rawseti(L, -2, 1);
	for (i=1; i<argc; ++i)
	{
		lua_pushstring(L, argv[i]);
		lua_rawseti(L, -2, i + 1);
	}

	{
		double t2;
		script_call_t1 = td_timestamp();
		res = lua_pcall(L, /*narg:*/2, /*nres:*/0, /*errorfunc:*/ -4);
		t2 = td_timestamp();
		if (global_tundra_stats)
			printf("total time spent in tundra: %.4fs\n", t2 - script_call_t1);
	}

	if (res == 0)
	{
		rc = global_tundra_exit_code;
	}
	else
	{
		fprintf(stderr, "%s\n", lua_tostring(L, -1));
		rc = 1;
	}

	lua_close(L);

	td_bin_allocator_cleanup(&bin_alloc);

	return rc;
}
Пример #23
0
// __depersist metamethod handler
static int l_str_depersist(lua_State *L)
{
    lua_settop(L, 2);
    lua_insert(L, 1);
    LuaPersistReader *pReader = (LuaPersistReader*)lua_touserdata(L, 1);

    // Read the instructions for re-creating the value
    if(!pReader->readStackObject())
        return 0;
    if(lua_type(L, 3) == LUA_TBOOLEAN && lua_toboolean(L, 3) == 1)
    {
        // The current code uses a boolean marker to indicate that the
        // instructions were stored in the environment. Replace the marker
        // with them.
        lua_getfenv(L, 2);
        lua_replace(L, 3);
    }
    else
    {
        // Older versions of the code wrote the instructions here, or nil for
        // no instructions. Convert nil to the empty table, and store the
        // instructions as the userdata's environment.
        if(lua_type(L, 3) == LUA_TNIL)
        {
            lua_newtable(L);
            lua_replace(L, 3);
        }
        lua_pushvalue(L, 3);
        lua_setfenv(L, 2);
    }

    // Prepare t, k for saving the value
    aux_push_weak_table(L, 0);
    lua_pushvalue(L, 2);

    if(lua_objlen(L, 3) == 0)
    {
        // No instructions provided, so read the value itself
        if(!pReader->readStackObject())
            return 0;
    }
    else
    {
        // The instructions are a table of values; unpack them and replace
        // proxies with their values.
        bool bIsIndexOperation = false;
        int iCount = (int)lua_objlen(L, 3);
        lua_checkstack(L, iCount + 1);
        for(int i = 1; i <= iCount; ++i)
        {
            lua_rawgeti(L, 3, i);
            if(lua_type(L, -1) == LUA_TUSERDATA)
            {
                if(i == 1)
                    bIsIndexOperation = true;
                lua_rawget(L, 4);
            }
        }

        if(iCount == 2 && bIsIndexOperation)
        {
            // If there were two values, and the first was a proxy, then the
            // instruction is to perform a table lookup.
            lua_gettable(L, -2);
            lua_replace(L, -2);
        }
        else
        {
            // Otherwise, the first value was a method or method name.
            if(lua_type(L, 6) != LUA_TFUNCTION)
            {
                lua_pushvalue(L, 6);
                lua_gettable(L, 7);
                lua_replace(L, 6);
            }
            lua_call(L, iCount - 1, 1);
        }
    }

    // Save the value
    lua_rawset(L, 4);
    return 0;
}
Пример #24
0
void luasrc_LoadEntities (const char *path)
{
	FileFindHandle_t fh;

	if ( !path )
	{
		path = "";
	}

	char root[ MAX_PATH ] = { 0 };

	char filename[ MAX_PATH ] = { 0 };
	char fullpath[ MAX_PATH ] = { 0 };
	char className[ 255 ] = { 0 };

	Q_snprintf( root, sizeof( root ), "%s" LUA_PATH_ENTITIES "\\*", path );

	char const *fn = g_pFullFileSystem->FindFirstEx( root, "MOD", &fh );
	while ( fn )
	{
		Q_strcpy( className, fn );
		Q_strlower( className );
		if ( fn[0] != '.' )
		{
			if ( g_pFullFileSystem->FindIsDirectory( fh ) )
			{
#ifdef CLIENT_DLL
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_ENTITIES "\\%s\\cl_init.lua", path, className );
#else
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_ENTITIES "\\%s\\init.lua", path, className );
#endif
				if ( filesystem->FileExists( filename, "MOD" ) )
				{
					filesystem->RelativePathToFullPath( filename, "MOD", fullpath, sizeof( fullpath ) );
					lua_newtable( L );
					char entDir[ MAX_PATH ];
					Q_snprintf( entDir, sizeof( entDir ), "entities\\%s", className );
					lua_pushstring( L, entDir );
					lua_setfield( L, -2, "__folder" );
					lua_pushstring( L, LUA_BASE_ENTITY_CLASS );
					lua_setfield( L, -2, "__base" );
					lua_pushstring( L, LUA_BASE_ENTITY_FACTORY );
					lua_setfield( L, -2, "__factory" );
					lua_setglobal( L, "ENT" );
					if ( luasrc_dofile( L, fullpath ) == 0 )
					{
						lua_getglobal( L, "entity" );
						if ( lua_istable( L, -1 ) )
						{
							lua_getfield( L, -1, "register" );
							if ( lua_isfunction( L, -1 ) )
							{
								lua_remove( L, -2 );
								lua_getglobal( L, "ENT" );
								lua_pushstring( L, className );
								luasrc_pcall( L, 2, 0, 0 );
								lua_getglobal( L, "ENT" );
								if ( lua_istable( L, -1 ) )
								{
									lua_getfield( L, -1, "__factory" );
									if ( lua_isstring( L, -1 ) )
									{
										const char *pszClassname = lua_tostring( L, -1 );
										if (Q_strcmp(pszClassname, "CBaseAnimating") == 0)
											RegisterScriptedEntity( className );
#ifndef CLIENT_DLL
										else if (Q_strcmp(pszClassname, "CBaseTrigger") == 0)
											RegisterScriptedTrigger( className );
#endif
									}
									lua_pop( L, 2 );
								}
								else
								{
									lua_pop( L, 1 );
								}
							}
							else
							{
								lua_pop( L, 2 );
							}
						}
						else
						{
							lua_pop( L, 1 );
						}
					}
					lua_pushnil( L );
					lua_setglobal( L, "ENT" );
				}
			}
		}

		fn = g_pFullFileSystem->FindNext( fh );
	}
	g_pFullFileSystem->FindClose( fh );
}
Пример #25
0
static int luv_constants(lua_State* L) {
  lua_newtable(L);

  // File open bitwise flags O_*
#ifdef O_RDONLY
  lua_pushinteger(L, O_RDONLY);
  lua_setfield(L, -2, "O_RDONLY");
#endif
#ifdef O_WRONLY
  lua_pushinteger(L, O_WRONLY);
  lua_setfield(L, -2, "O_WRONLY");
#endif
#ifdef O_RDWR
  lua_pushinteger(L, O_RDWR);
  lua_setfield(L, -2, "O_RDWR");
#endif
#ifdef O_APPEND
  lua_pushinteger(L, O_APPEND);
  lua_setfield(L, -2, "O_APPEND");
#endif
#ifdef O_CREAT
  lua_pushinteger(L, O_CREAT);
  lua_setfield(L, -2, "O_CREAT");
#endif
#ifdef O_DSYNC
  lua_pushinteger(L, O_DSYNC);
  lua_setfield(L, -2, "O_DSYNC");
#endif
#ifdef O_EXCL
  lua_pushinteger(L, O_EXCL);
  lua_setfield(L, -2, "O_EXCL");
#endif
#ifdef O_EXLOCK
  lua_pushinteger(L, O_EXLOCK);
  lua_setfield(L, -2, "O_EXLOCK");
#endif
#ifdef O_NOCTTY
  lua_pushinteger(L, O_NOCTTY);
  lua_setfield(L, -2, "O_NOCTTY");
#endif
#ifdef O_NONBLOCK
  lua_pushinteger(L, O_NONBLOCK);
  lua_setfield(L, -2, "O_NONBLOCK");
#endif
#ifdef O_RSYNC
  lua_pushinteger(L, O_RSYNC);
  lua_setfield(L, -2, "O_RSYNC");
#endif
#ifdef O_SYNC
  lua_pushinteger(L, O_SYNC);
  lua_setfield(L, -2, "O_SYNC");
#endif
#ifdef O_TRUNC
  lua_pushinteger(L, O_TRUNC);
  lua_setfield(L, -2, "O_TRUNC");
#endif

  // Socket types SOCK_*
#ifdef SOCK_STREAM
  lua_pushinteger(L, SOCK_STREAM);
  lua_setfield(L, -2, "SOCK_STREAM");
#endif
#ifdef SOCK_DGRAM
  lua_pushinteger(L, SOCK_DGRAM);
  lua_setfield(L, -2, "SOCK_DGRAM");
#endif
#ifdef SOCK_SEQPACKET
  lua_pushinteger(L, SOCK_SEQPACKET);
  lua_setfield(L, -2, "SOCK_SEQPACKET");
#endif
#ifdef SOCK_RAW
  lua_pushinteger(L, SOCK_RAW);
  lua_setfield(L, -2, "SOCK_RAW");
#endif
#ifdef SOCK_RDM
  lua_pushinteger(L, SOCK_RDM);
  lua_setfield(L, -2, "SOCK_RDM");
#endif

  // AF_*
#ifdef AF_UNIX
  lua_pushinteger(L, AF_UNIX);
  lua_setfield(L, -2, "AF_UNIX");
#endif
#ifdef AF_INET
  lua_pushinteger(L, AF_INET);
  lua_setfield(L, -2, "AF_INET");
#endif
#ifdef AF_INET6
  lua_pushinteger(L, AF_INET6);
  lua_setfield(L, -2, "AF_INET6");
#endif
#ifdef AF_IPX
  lua_pushinteger(L, AF_IPX);
  lua_setfield(L, -2, "AF_IPX");
#endif
#ifdef AF_NETLINK
  lua_pushinteger(L, AF_NETLINK);
  lua_setfield(L, -2, "AF_NETLINK");
#endif
#ifdef AF_X25
  lua_pushinteger(L, AF_X25);
  lua_setfield(L, -2, "AF_X25");
#endif
#ifdef AF_AX25
  lua_pushinteger(L, AF_AX25);
  lua_setfield(L, -2, "AF_AX25");
#endif
#ifdef AF_ATMPVC
  lua_pushinteger(L, AF_ATMPVC);
  lua_setfield(L, -2, "AF_ATMPVC");
#endif
#ifdef AF_APPLETALK
  lua_pushinteger(L, AF_APPLETALK);
  lua_setfield(L, -2, "AF_APPLETALK");
#endif
#ifdef AF_PACKET
  lua_pushinteger(L, AF_PACKET);
  lua_setfield(L, -2, "AF_PACKET");
#endif

  // AI_*
#ifdef AI_ADDRCONFIG
  lua_pushinteger(L, AI_ADDRCONFIG);
  lua_setfield(L, -2, "AI_ADDRCONFIG");
#endif
#ifdef AI_V4MAPPED
  lua_pushinteger(L, AI_V4MAPPED);
  lua_setfield(L, -2, "AI_V4MAPPED");
#endif
#ifdef AI_ALL
  lua_pushinteger(L, AI_ALL);
  lua_setfield(L, -2, "AI_ALL");
#endif
#ifdef AI_NUMERICHOST
  lua_pushinteger(L, AI_NUMERICHOST);
  lua_setfield(L, -2, "AI_NUMERICHOST");
#endif
#ifdef AI_PASSIVE
  lua_pushinteger(L, AI_PASSIVE);
  lua_setfield(L, -2, "AI_PASSIVE");
#endif
#ifdef AI_NUMERICSERV
  lua_pushinteger(L, AI_NUMERICSERV);
  lua_setfield(L, -2, "AI_NUMERICSERV");
#endif

  // Signals
#ifdef SIGHUP
  lua_pushinteger(L, SIGHUP);
  lua_setfield(L, -2, "SIGHUP");
#endif
#ifdef SIGINT
  lua_pushinteger(L, SIGINT);
  lua_setfield(L, -2, "SIGINT");
#endif
#ifdef SIGQUIT
  lua_pushinteger(L, SIGQUIT);
  lua_setfield(L, -2, "SIGQUIT");
#endif
#ifdef SIGILL
  lua_pushinteger(L, SIGILL);
  lua_setfield(L, -2, "SIGILL");
#endif
#ifdef SIGTRAP
  lua_pushinteger(L, SIGTRAP);
  lua_setfield(L, -2, "SIGTRAP");
#endif
#ifdef SIGABRT
  lua_pushinteger(L, SIGABRT);
  lua_setfield(L, -2, "SIGABRT");
#endif
#ifdef SIGIOT
  lua_pushinteger(L, SIGIOT);
  lua_setfield(L, -2, "SIGIOT");
#endif
#ifdef SIGBUS
  lua_pushinteger(L, SIGBUS);
  lua_setfield(L, -2, "SIGBUS");
#endif
#ifdef SIGFPE
  lua_pushinteger(L, SIGFPE);
  lua_setfield(L, -2, "SIGFPE");
#endif
#ifdef SIGKILL
  lua_pushinteger(L, SIGKILL);
  lua_setfield(L, -2, "SIGKILL");
#endif
#ifdef SIGUSR1
  lua_pushinteger(L, SIGUSR1);
  lua_setfield(L, -2, "SIGUSR1");
#endif
#ifdef SIGSEGV
  lua_pushinteger(L, SIGSEGV);
  lua_setfield(L, -2, "SIGSEGV");
#endif
#ifdef SIGUSR2
  lua_pushinteger(L, SIGUSR2);
  lua_setfield(L, -2, "SIGUSR2");
#endif
#ifdef SIGPIPE
  lua_pushinteger(L, SIGPIPE);
  lua_setfield(L, -2, "SIGPIPE");
#endif
#ifdef SIGALRM
  lua_pushinteger(L, SIGALRM);
  lua_setfield(L, -2, "SIGALRM");
#endif
#ifdef SIGTERM
  lua_pushinteger(L, SIGTERM);
  lua_setfield(L, -2, "SIGTERM");
#endif
#ifdef SIGCHLD
  lua_pushinteger(L, SIGCHLD);
  lua_setfield(L, -2, "SIGCHLD");
#endif
#ifdef SIGSTKFLT
  lua_pushinteger(L, SIGSTKFLT);
  lua_setfield(L, -2, "SIGSTKFLT");
#endif
#ifdef SIGCONT
  lua_pushinteger(L, SIGCONT);
  lua_setfield(L, -2, "SIGCONT");
#endif
#ifdef SIGSTOP
  lua_pushinteger(L, SIGSTOP);
  lua_setfield(L, -2, "SIGSTOP");
#endif
#ifdef SIGTSTP
  lua_pushinteger(L, SIGTSTP);
  lua_setfield(L, -2, "SIGTSTP");
#endif
#ifdef SIGBREAK
  lua_pushinteger(L, SIGBREAK);
  lua_setfield(L, -2, "SIGBREAK");
#endif
#ifdef SIGTTIN
  lua_pushinteger(L, SIGTTIN);
  lua_setfield(L, -2, "SIGTTIN");
#endif
#ifdef SIGTTOU
  lua_pushinteger(L, SIGTTOU);
  lua_setfield(L, -2, "SIGTTOU");
#endif
#ifdef SIGURG
  lua_pushinteger(L, SIGURG);
  lua_setfield(L, -2, "SIGURG");
#endif
#ifdef SIGXCPU
  lua_pushinteger(L, SIGXCPU);
  lua_setfield(L, -2, "SIGXCPU");
#endif
#ifdef SIGXFSZ
  lua_pushinteger(L, SIGXFSZ);
  lua_setfield(L, -2, "SIGXFSZ");
#endif
#ifdef SIGVTALRM
  lua_pushinteger(L, SIGVTALRM);
  lua_setfield(L, -2, "SIGVTALRM");
#endif
#ifdef SIGPROF
  lua_pushinteger(L, SIGPROF);
  lua_setfield(L, -2, "SIGPROF");
#endif
#ifdef SIGWINCH
  lua_pushinteger(L, SIGWINCH);
  lua_setfield(L, -2, "SIGWINCH");
#endif
#ifdef SIGIO
  lua_pushinteger(L, SIGIO);
  lua_setfield(L, -2, "SIGIO");
#endif
#ifdef SIGPOLL
  lua_pushinteger(L, SIGPOLL);
  lua_setfield(L, -2, "SIGPOLL");
#endif
#ifdef SIGLOST
  lua_pushinteger(L, SIGLOST);
  lua_setfield(L, -2, "SIGLOST");
#endif
#ifdef SIGPWR
  lua_pushinteger(L, SIGPWR);
  lua_setfield(L, -2, "SIGPWR");
#endif
#ifdef SIGSYS
  lua_pushinteger(L, SIGSYS);
  lua_setfield(L, -2, "SIGSYS");
#endif
  return 1;
}
Пример #26
0
void luasrc_LoadWeapons (const char *path)
{
	FileFindHandle_t fh;

	if ( !path )
	{
		path = "";
	}

	char root[ MAX_PATH ] = { 0 };

	char filename[ MAX_PATH ] = { 0 };
	char fullpath[ MAX_PATH ] = { 0 };
	char className[ MAX_WEAPON_STRING ] = { 0 };

	Q_snprintf( root, sizeof( root ), "%s" LUA_PATH_WEAPONS "\\*", path );

	char const *fn = g_pFullFileSystem->FindFirstEx( root, "MOD", &fh );
	while ( fn )
	{
		Q_strcpy( className, fn );
		Q_strlower( className );
		if ( fn[0] != '.' )
		{
			if ( g_pFullFileSystem->FindIsDirectory( fh ) )
			{
#ifdef CLIENT_DLL
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_WEAPONS "\\%s\\cl_init.lua", path, className );
#else
				Q_snprintf( filename, sizeof( filename ), "%s" LUA_PATH_WEAPONS "\\%s\\init.lua", path, className );
#endif
				if ( filesystem->FileExists( filename, "MOD" ) )
				{
					filesystem->RelativePathToFullPath( filename, "MOD", fullpath, sizeof( fullpath ) );
					lua_newtable( L );
					char entDir[ MAX_PATH ];
					Q_snprintf( entDir, sizeof( entDir ), "weapons\\%s", className );
					lua_pushstring( L, entDir );
					lua_setfield( L, -2, "__folder" );
					lua_pushstring( L, LUA_BASE_WEAPON );
					lua_setfield( L, -2, "__base" );
					lua_setglobal( L, "SWEP" );
					if ( luasrc_dofile( L, fullpath ) == 0 )
					{
						lua_getglobal( L, "weapon" );
						if ( lua_istable( L, -1 ) )
						{
							lua_getfield( L, -1, "register" );
							if ( lua_isfunction( L, -1 ) )
							{
								lua_remove( L, -2 );
								lua_getglobal( L, "SWEP" );
								lua_pushstring( L, className );
								luasrc_pcall( L, 2, 0, 0 );
								RegisterScriptedWeapon( className );
							}
							else
							{
								lua_pop( L, 2 );
							}
						}
						else
						{
							lua_pop( L, 1 );
						}
					}
					lua_pushnil( L );
					lua_setglobal( L, "SWEP" );
				}
			}
		}

		fn = g_pFullFileSystem->FindNext( fh );
	}
	g_pFullFileSystem->FindClose( fh );
}
Пример #27
0
void storage_store(const char *key, const char *value)
{
	long filesize;
	FILE *file = NULL;
	const char *stored_data;
	lua_State *L;

	assert(key);
	assert(value);

	L = luaL_newstate();
	if (!L)
		log_oom_and_exit();

	file = fopen(".storage", "r");
	if (file) {
		fseek(file, 0L, SEEK_END);
		filesize = ftell(file);
		fseek(file, 0L, SEEK_SET);

		if (filesize > 0) {
			// If there is something in the file, we mmap it and decode it to create a table
			int r;
			char *data = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fileno(file), 0);
			if (data == MAP_FAILED) {
				goto finish;
			}

			lua_pushcfunction(L, json_decode);
			lua_pushstring(L, data);
			call_lua_function(L, 1, 1);

			r = munmap(data, filesize);
			if (r < 0) {
				lua_pop(L, 1);
				goto finish;
			}
		}
		fclose(file);
	} else {
		lua_newtable(L);
	}

	file = fopen(".storage", "w");
	if (!file) {
		goto finish;
	}

	// add the new element to the table
	lua_pushstring(L, value);
	lua_setfield(L, -2, key);

	// encode the table in json
	lua_pushcfunction(L, json_encode);
	lua_pushvalue(L, 1);
	call_lua_function(L, 1, 1);

	// store this in the file
	if (lua_isnil(L, -1)) {
		lua_pop(L, 2);
		goto finish;
	}
	stored_data = luaL_checkstring(L, -1);
	fputs(stored_data, file);

	// pop the table and the string
	lua_pop(L, 2);

finish:
	if (file) {
		fclose(file);
	}
	assert(lua_gettop(L) == 0);
	lua_close(L);
}
Пример #28
0
 LuaTable(lua_State* luaState)
     : m_luaState(luaState) {
     lua_newtable(m_luaState);
     m_index = lua_gettop(m_luaState);
 }
Пример #29
0
void push_hit_params(lua_State *L,const HitParams &params)
{
	lua_newtable(L);
	setintfield(L, -1, "hp", params.hp);
	setintfield(L, -1, "wear", params.wear);
}
Пример #30
0
static void json_create_config(lua_State *l)
{
    json_config_t *cfg;
    int i;

    cfg = lua_newuserdata(l, sizeof(*cfg));

    /* Create GC method to clean up strbuf */
    lua_newtable(l);
    lua_pushcfunction(l, json_destroy_config);
    lua_setfield(l, -2, "__gc");
    lua_setmetatable(l, -2);

    strbuf_init(&cfg->encode_buf, 0);

    cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
    cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
    cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
    cfg->encode_max_depth = DEFAULT_MAX_DEPTH;
    cfg->encode_refuse_badnum = DEFAULT_ENCODE_REFUSE_BADNUM;
    cfg->decode_refuse_badnum = DEFAULT_DECODE_REFUSE_BADNUM;
    cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
    json_set_number_precision(cfg, 14);

    /* Decoding init */

    /* Tag all characters as an error */
    for (i = 0; i < 256; i++)
        cfg->ch2token[i] = T_ERROR;

    /* Set tokens that require no further processing */
    cfg->ch2token['{'] = T_OBJ_BEGIN;
    cfg->ch2token['}'] = T_OBJ_END;
    cfg->ch2token['['] = T_ARR_BEGIN;
    cfg->ch2token[']'] = T_ARR_END;
    cfg->ch2token[','] = T_COMMA;
    cfg->ch2token[':'] = T_COLON;
    cfg->ch2token['\0'] = T_END;
    cfg->ch2token[' '] = T_WHITESPACE;
    cfg->ch2token['\t'] = T_WHITESPACE;
    cfg->ch2token['\n'] = T_WHITESPACE;
    cfg->ch2token['\r'] = T_WHITESPACE;

    /* Update characters that require further processing */
    cfg->ch2token['f'] = T_UNKNOWN;     /* false? */
    cfg->ch2token['i'] = T_UNKNOWN;     /* inf, ininity? */
    cfg->ch2token['I'] = T_UNKNOWN;
    cfg->ch2token['n'] = T_UNKNOWN;     /* null, nan? */
    cfg->ch2token['N'] = T_UNKNOWN;
    cfg->ch2token['t'] = T_UNKNOWN;     /* true? */
    cfg->ch2token['"'] = T_UNKNOWN;     /* string? */
    cfg->ch2token['+'] = T_UNKNOWN;     /* number? */
    cfg->ch2token['-'] = T_UNKNOWN;
    for (i = 0; i < 10; i++)
        cfg->ch2token['0' + i] = T_UNKNOWN;

    /* Lookup table for parsing escape characters */
    for (i = 0; i < 256; i++)
        cfg->escape2char[i] = 0;          /* String error */
    cfg->escape2char['"'] = '"';
    cfg->escape2char['\\'] = '\\';
    cfg->escape2char['/'] = '/';
    cfg->escape2char['b'] = '\b';
    cfg->escape2char['t'] = '\t';
    cfg->escape2char['n'] = '\n';
    cfg->escape2char['f'] = '\f';
    cfg->escape2char['r'] = '\r';
    cfg->escape2char['u'] = 'u';          /* Unicode parsing required */


#if 0
    /* Initialise separate storage for pre-generated escape codes.
     * Escapes 0-31 map directly, 34, 92, 127 follow afterwards to
     * save memory. */
    for (i = 0 ; i < 32; i++)
        sprintf(cfg->escapes[i], "\\u%04x", i);
    strcpy(cfg->escapes[8], "\b");              /* Override simpler escapes */
    strcpy(cfg->escapes[9], "\t");
    strcpy(cfg->escapes[10], "\n");
    strcpy(cfg->escapes[12], "\f");
    strcpy(cfg->escapes[13], "\r");
    strcpy(cfg->escapes[32], "\\\"");           /* chr(34) */
    strcpy(cfg->escapes[33], "\\\\");           /* chr(92) */
    sprintf(cfg->escapes[34], "\\u%04x", 127);  /* char(127) */

    /* Initialise encoding escape lookup table */
    for (i = 0; i < 32; i++)
        cfg->char2escape[i] = cfg->escapes[i];
    for (i = 32; i < 256; i++)
        cfg->char2escape[i] = NULL;
    cfg->char2escape[34] = cfg->escapes[32];
    cfg->char2escape[92] = cfg->escapes[33];
    cfg->char2escape[127] = cfg->escapes[34];
#endif
}