Esempio n. 1
0
int merger_room_index( lua_State *L )
{
   ROOM_DATA *room;
   EXIT_DATA *spexit;
   const char *field;
   
   if ( !lua_isuserdata( L, 1 ) )
     {
        lua_pushstring( L, "Indexing non-userdata. Internal error!" );
        lua_error( L );
     }
   
   if ( !lua_isstring( L, 2 ) )
     {
        lua_pushstring( L, "Cannot index a room-userdata with a non-string." );
        lua_error( L );
     }
   
   room = *(ROOM_DATA**) lua_touserdata( L, 1 );
   field = lua_tostring( L, 2 );
   
   if ( !strcmp( field, "name" ) || !strcmp( field, "title" ) )
     {
        lua_pushstring( L, room->name );
     }
   else if ( !strcmp( field, "vnum" ) )
     {
        lua_pushinteger( L, room->vnum );
     }
   else if ( !strcmp( field, "underwater" ) )
     {
        lua_pushboolean( L, room->underwater );
     }
   else if ( !strcmp( field, "pf_next" ) )
     {
        merger_push_room( L, room->pf_parent );
     }
   else if ( !strcmp( field, "pf_command" ) )
     {
        if ( room->pf_direction == 0 || !room->pf_parent )
          lua_pushnil( L );
        else if ( room->pf_direction > 0 )
          lua_pushstring( L, dir_name[room->pf_direction] );
        else
          {
             for ( spexit = room->special_exits; spexit; spexit = spexit->next )
               if ( spexit->to == room->pf_parent )
                 break;
             
             if ( spexit && spexit->command )
               lua_pushstring( L, spexit->command );
             else
               lua_pushnil( L );
          }
     }
   else if ( !strcmp( field, "exits" ) )
     {
        ROOM_DATA **r;
        
        r = (ROOM_DATA**) lua_newuserdata( L, sizeof(ROOM_DATA*) );
        *r = room;
        
        lua_getfield( L, LUA_REGISTRYINDEX, "merger_exits_metatable" );
        lua_setmetatable( L, -2 );
     }
   else if ( !strcmp( field, "special_exits" ) )
     {
        ROOM_DATA **r;
        
        r = (ROOM_DATA**) lua_newuserdata( L, sizeof(ROOM_DATA*) );
        *r = room;
        
        lua_getfield( L, LUA_REGISTRYINDEX, "merger_spexits_metatable" );
        lua_setmetatable( L, -2 );
     }
   else if ( !strcmp( field, "area" ) )
     {
        AREA_DATA **a;
        
        if ( !room->area )
          lua_pushnil( L );
        else
          {
             a = (AREA_DATA**) lua_newuserdata( L, sizeof(AREA_DATA*) );
             *a = room->area;
             
             lua_getfield( L, LUA_REGISTRYINDEX, "merger_area_metatable" );
             lua_setmetatable( L, -2 );
          }
     }
   else if ( !strcmp( field, "environment" ) || !strcmp( field, "type" ) )
     {
        ROOM_TYPE **t;
        
        if ( !room->room_type )
          lua_pushnil( L );
        else
          {
             t = (ROOM_TYPE**) lua_newuserdata( L, sizeof(ROOM_TYPE*) );
             *t = room->room_type;
             
             lua_getfield( L, LUA_REGISTRYINDEX, "merger_environment_metatable" );
             lua_setmetatable( L, -2 );
          }
     }
   else
     {
        int dir;
        
        /* room.east; Shortcut to room.exits.east.room. */
        for ( dir = 1; dir_name[dir]; dir++ )
          if ( !strcmp( dir_name[dir], field ) ||
               !strcmp( dir_small_name[dir], field ) )
            break;
        
        if ( dir_name[dir] )
          merger_push_room( L, room->exits[dir] );
        else
          lua_pushnil( L );
     }
   
   return 1;
}
Esempio n. 2
0
int static l_graphics_newShader(lua_State* state) {
  char const* vertexSrc = l_tools_toStringOrError(state, 1);
  char const* fragmentSrc = NULL;
  char * loadedFile1 = NULL;
  char * loadedFile2 = NULL;

  if(lua_isstring(state, 2)) {
    fragmentSrc = lua_tostring(state, 2);
    
    if(!isVertexShader(vertexSrc)) {
      // TODO
      int loadedFile1Size = filesystem_read(vertexSrc, &loadedFile1);
      (void) loadedFile1Size;
      if(!loadedFile1 || !isVertexShader(loadedFile1)) {
        free(loadedFile1);
        lua_pushstring(state, "input 1 is not a valid vertex shader");
        return lua_error(state);
      }
      vertexSrc = loadedFile1;
    }

    if(!isSingleFragmentShader(fragmentSrc)) {
      // TODO
      int loadedFile2Size = filesystem_read(fragmentSrc, &loadedFile2);
      (void)loadedFile2Size;

      if(!loadedFile2 || !isSingleFragmentShader(loadedFile2)) {
        free(loadedFile1);
        free(loadedFile2);
        lua_pushstring(state, "input 2 is not a valid fragment shader");
        return lua_error(state);
      }
      fragmentSrc = loadedFile2;
    }

  } else {
    if(isVertexShader(vertexSrc)) {
      // nothing required
    } else if(isSingleFragmentShader(vertexSrc)) {
      fragmentSrc = vertexSrc;
      vertexSrc = NULL;
    } else {
      // TODO
      int loadedFile1Size = filesystem_read(vertexSrc, &loadedFile1);
      (void) loadedFile1Size;
      if(!loadedFile1) {
        lua_pushstring(state, "could not open file");
        return lua_error(state);
      }

      if(isSingleFragmentShader(loadedFile1)) {
        fragmentSrc = loadedFile1;
        vertexSrc = NULL;
      } else if(isVertexShader(loadedFile1)) {
        vertexSrc = loadedFile1;
        fragmentSrc = NULL;
      } else {
        free(loadedFile1);
        lua_pushstring(state, "input is not a valid shader");
        return lua_error(state);
      }
    }
  }

  l_graphics_Shader * shader = lua_newuserdata(state, sizeof(l_graphics_Shader));
  graphics_ShaderCompileStatus status = graphics_Shader_new(&shader->shader, vertexSrc, fragmentSrc);
  if(status != graphics_ShaderCompileStatus_okay) {
    pushShaderInfoLog(state, &shader->shader);
    return lua_error(state);
  }

  lua_rawgeti(state, LUA_REGISTRYINDEX, moduleData.shaderMT);
  lua_setmetatable(state, -2);

  free(loadedFile1);
  free(loadedFile2);

  int const textureUnits = shader->shader.textureUnitCount;
  shader->referencedTextures = malloc(textureUnits * sizeof(int));
  for(int i = 0; i < textureUnits; ++i) {
    shader->referencedTextures[i] = LUA_NOREF;
  }

  return 1;
}
Esempio n. 3
0
static int vlclua_node_add_subitem( lua_State *L )
{
    services_discovery_t *p_sd = (services_discovery_t *)vlclua_get_this( L );
    input_item_t **pp_node = (input_item_t **)luaL_checkudata( L, 1, "node" );
    if( *pp_node )
    {
        if( lua_istable( L, -1 ) )
        {
            lua_getfield( L, -1, "path" );
            if( lua_isstring( L, -1 ) )
            {
                const char *psz_path = lua_tostring( L, -1 );

                /* The table must be at the top of the stack when calling
                 * vlclua_read_options() */
                char **ppsz_options = NULL;
                int i_options = 0;
                lua_pushvalue( L, -2 );
                vlclua_read_options( p_sd, L, &i_options, &ppsz_options );

                input_item_t *p_input = input_item_NewExt( psz_path,
                                                           psz_path, i_options,
                                                           (const char **)ppsz_options,
                                                           VLC_INPUT_OPTION_TRUSTED, -1 );
                lua_pop( L, 2 );

                if( p_input )
                {
                    input_item_node_t *p_input_node = input_item_node_Create( *pp_node );

                    vlclua_read_meta_data( p_sd, L, p_input );
                    /* This one is to be tested... */
                    vlclua_read_custom_meta_data( p_sd, L, p_input );
                    lua_getfield( L, -1, "duration" );
                    if( lua_isnumber( L, -1 ) )
                        input_item_SetDuration( p_input, (lua_tonumber( L, -1 )*1e6) );
                    else if( !lua_isnil( L, -1 ) )
                        msg_Warn( p_sd, "Item duration should be a number (in seconds)." );
                    lua_pop( L, 1 );
                    input_item_node_AppendItem( p_input_node, p_input );
                    input_item_node_PostAndDelete( p_input_node );
                    input_item_t **udata = (input_item_t **)
                                           lua_newuserdata( L, sizeof( input_item_t * ) );
                    *udata = p_input;
                    if( luaL_newmetatable( L, "input_item_t" ) )
                    {
                        lua_newtable( L );
                        luaL_register( L, NULL, vlclua_item_reg );
                        lua_setfield( L, -2, "__index" );
                        lua_pushliteral( L, "none of your business" );
                        lua_setfield( L, -2, "__metatable" );
                    }
                    lua_setmetatable( L, -2 );
                    vlc_gc_decref( p_input );
                }
                while( i_options > 0 )
                    free( ppsz_options[--i_options] );
                free( ppsz_options );
            }
            else
                msg_Err( p_sd, "node:add_subitem: the \"path\" parameter can't be empty" );
        }
        else
            msg_Err( p_sd, "Error parsing add_subitem arguments" );
    }
    return 1;
}
Esempio n. 4
0
/* Lua only functions */
int luaT_lua_newmetatable(lua_State *L)
{
  const char* tname = luaL_checkstring(L, 1);
  const void *id;

  lua_settop(L, 5);
  luaL_argcheck(L, lua_isnoneornil(L, 2) || lua_isstring(L, 2), 2, "parent class name or nil expected");
  luaL_argcheck(L, lua_isnoneornil(L, 3) || lua_isfunction(L, 3), 3, "constructor function or nil expected");
  luaL_argcheck(L, lua_isnoneornil(L, 4) || lua_isfunction(L, 4), 4, "destructor function or nil expected");
  luaL_argcheck(L, lua_isnoneornil(L, 5) || lua_isfunction(L, 5), 5, "factory function or nil expected");

  if(luaT_classmodulename(tname))
    lua_getfield(L, LUA_GLOBALSINDEX, luaT_classmodulename(tname));
  else
    lua_pushvalue(L, LUA_GLOBALSINDEX);
  if(!lua_istable(L, 6))
    luaL_error(L, "while creating metatable %s: bad argument #1 (%s is an invalid module name)", tname, luaT_classmodulename(tname));

  /* we first create the new metaclass if we have to */
  if(!luaT_typename2id(L, tname))
  {
    /* create the metaclass */
    lua_newtable(L);
    id = lua_topointer(L, -1); /* id = pointer on metaclass */

    /* __index points on itself */
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");

    /* new points to constructor */
    lua_pushvalue(L, 3);
    lua_setfield(L, -2, "new");

    /* __typename contains the typename */
    lua_pushstring(L, tname);
    lua_setfield(L, -2, "__typename");

    /* by default, __version equals 1 */
    lua_pushnumber(L, 1);
    lua_setfield(L, -2, "__version");

    /* register in "*torch.id2tname*" registry table 
       (id -> typename) */
    lua_getfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*");
    if(lua_isnil(L, -1))
    {
      lua_pop(L, 1);
      lua_newtable(L);
      lua_setfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*");
      lua_getfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*");
    }
    lua_pushlightuserdata(L, (void*)id);
    lua_pushstring(L, tname);
    lua_settable(L, -3);
    lua_pop(L, 1);

    /* register in "*torch.tname2id*" registry table 
       (typename -> id) */
    lua_getfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*");
    if(lua_isnil(L, -1))
    {
      lua_pop(L, 1);
      lua_newtable(L);
      lua_setfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*");
      lua_getfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*");
    }
    lua_pushstring(L, tname);
    lua_pushlightuserdata(L, (void*)id);
    lua_settable(L, -3);
    lua_pop(L, 1);
  }

  /* we retrieve the existing metaclass */
  else
  {
    id = luaT_typename2id(L, tname);
    luaT_pushmetaclass(L, id);
  }

  /* we assign the parent class if necessary */
  if(!lua_isnoneornil(L, 2))
  {
    if(lua_getmetatable(L, -1))
      luaL_error(L, "class %s has been already assigned a parent class\n", tname);
    else
    {
      const char* parenttname = luaL_checkstring(L, 2);
      luaT_pushmetaclass(L, luaT_typename2id(L, parenttname));
      if(lua_isnil(L, -1))
        luaL_error(L, "bad argument #2 (invalid parent class name %s)", parenttname);
      lua_setmetatable(L, -2);
    }
  }

  /******** root-metatable ********/

  /* id is the pointer on the metatable
     registry[id] = root-metatable, so try to see if it exists */

  lua_pushlightuserdata(L, (void*)id); /* id */
  lua_rawget(L, LUA_REGISTRYINDEX);

  /* not existing? we create a new one! */
  if(lua_isnil(L, -1))
  {
    lua_pop(L, 1); /* remove nil on stack */
    lua_newtable(L);
    
    /* __index handling */
    lua_pushcfunction(L, luaT_rmt__index);
    lua_setfield(L, -2, "__index");
    
    /* __newindex handling */
    lua_pushcfunction(L, luaT_rmt__newindex);
    lua_setfield(L, -2, "__newindex");

    /* __metatable field (point on the metaclass) */
    lua_pushvalue(L, -2);
    lua_setfield(L, -2, "__metatable");

    /* __typename contains the typename */
    lua_pushstring(L, tname);
    lua_setfield(L, -2, "__typename");
    
    /* operators handling */
#define MT_ADD_OPERATOR(name) \
  lua_pushcfunction(L, luaT_rmt__##name); \
  lua_setfield(L, -2, "__" #name)
    
    MT_ADD_OPERATOR(tostring);
    MT_ADD_OPERATOR(add);
    MT_ADD_OPERATOR(sub);
    MT_ADD_OPERATOR(mul);
    MT_ADD_OPERATOR(div);
    MT_ADD_OPERATOR(mod);
    MT_ADD_OPERATOR(pow);
    MT_ADD_OPERATOR(unm);
    MT_ADD_OPERATOR(concat);
    MT_ADD_OPERATOR(len);
    MT_ADD_OPERATOR(eq);
    MT_ADD_OPERATOR(lt);
    MT_ADD_OPERATOR(le);
    MT_ADD_OPERATOR(call);
    
    /* assign the metaclass as metatable... */
    lua_pushvalue(L, -2);
    lua_setmetatable(L, -2);

    /* id is the pointer on the metatable
       set registry[id] = root-metatable */
    lua_pushlightuserdata(L, (void*)id); /* id */
    lua_pushvalue(L, -2);                /* metatable */
    lua_rawset(L, LUA_REGISTRYINDEX);    /* registry[id] = metatable */

  } /* ok, so now we have the root-metatable on the stack */

  /* register the destructor function  */
  if(!lua_isnoneornil(L, 4))
  {
    /* does it exists already? */
    lua_pushstring(L, "__gc");
    lua_rawget(L, -2);

    if(lua_isnil(L, -1))
    {
      lua_pop(L, 1); /* pop nil */
      lua_pushstring(L, "__gc");
      lua_pushvalue(L, 4);
      lua_rawset(L, -3);
    }
    else
      luaL_error(L, "%s has been already assigned a destructor", tname);
  }

  /* register the factory function  */
  if(!lua_isnoneornil(L, 5))
  {
    /* does it exists already? */
    lua_pushstring(L, "__factory");
    lua_rawget(L, -2);

    if(lua_isnil(L, -1))
    {
      lua_pop(L, 1); /* pop nil */
      lua_pushstring(L, "__factory");
      lua_pushvalue(L, 5);
      lua_rawset(L, -3);
    }
    else
      luaL_error(L, "%s has been already assigned a factory", tname);
  }

  /******** Constructor table and metatable ********/
  lua_pushstring(L, "__constructor");
  lua_rawget(L, -2);

  if(lua_isnil(L, -1))
  {
    lua_pop(L, 1);                        /* pop nil */
    lua_newtable(L);                      /* fancy table */
    lua_newtable(L);                      /* fancy metatable */

    lua_pushvalue(L, -4);                 /* metaclass */
    lua_setfield(L, -2, "__index");       /* so we can get the methods */

    lua_pushcfunction(L, luaT_cmt__newindex);
    lua_setfield(L, -2, "__newindex");    /* so we cannot messup */

    lua_pushcfunction(L, luaT_cmt__call);
    lua_setfield(L, -2, "__call");        /* so we can create */

    lua_pushvalue(L, -4); 
    lua_setfield(L, -2, "__metatable");   /* redirect to metatable with methods */

    lua_setmetatable(L, -2);              /* metatable is ... the fancy metatable */

    /* set root-metatable[__constructor] = constructor-metatable */
    lua_pushstring(L, "__constructor");
    lua_pushvalue(L, -2);
    lua_rawset(L, -4);
  }

  /* register the constructor function  */
  if(!lua_isnoneornil(L, 3))
  {
    /* get constructor metatable */
    lua_getmetatable(L, -1);

    /* does it exists already? */
    lua_pushstring(L, "__new");
    lua_rawget(L, -2);

    if(lua_isnil(L, -1))
    {
      lua_pop(L, 1); /* pop nil */
      lua_pushstring(L, "__new");
      lua_pushvalue(L, 3);
      lua_rawset(L, -3);
    }
    else
      luaL_error(L, "%s has been already assigned a constructor", tname);

    /* pop constructor metatable */
    lua_pop(L, 1);
  }
  
  lua_setfield(L, 6, luaT_classrootname(tname)); /* module.name = constructor-metatable */
  lua_pop(L, 1);                        /* pop the root-metatable */

  return 1; /* returns the metaclass */
}
Esempio n. 5
0
	void LuaInstance::SetMetatable(int index) const
	{
		lua_setmetatable(m_state, index);
	}
static int
ngx_http_lua_ngx_resp_get_headers(lua_State *L)
{
    ngx_list_part_t    *part;
    ngx_table_elt_t    *header;
    ngx_http_request_t *r;
    u_char             *lowcase_key = NULL;
    size_t              lowcase_key_sz = 0;
    ngx_uint_t          i;
    int                 n;
    int                 max;
    int                 raw = 0;
    int                 count = 0;

    n = lua_gettop(L);

    if (n >= 1) {
        if (lua_isnil(L, 1)) {
            max = NGX_HTTP_LUA_MAX_HEADERS;

        } else {
            max = luaL_checkinteger(L, 1);
        }

        if (n >= 2) {
            raw = lua_toboolean(L, 2);
        }

    } else {
        max = NGX_HTTP_LUA_MAX_HEADERS;
    }

    r = ngx_http_lua_get_req(L);
    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    ngx_http_lua_check_fake_request(L, r);

    part = &r->headers_out.headers.part;
    count = part->nelts;
    while (part->next) {
        part = part->next;
        count += part->nelts;
    }

    if (max > 0 && count > max) {
        count = max;
        ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua exceeding request header limit %d", max);
    }

    lua_createtable(L, 0, count);

    if (!raw) {
        lua_pushlightuserdata(L, &ngx_http_lua_headers_metatable_key);
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_setmetatable(L, -2);
    }

#if 1
    if (r->headers_out.content_type.len) {
        lua_pushliteral(L, "content-type");
        lua_pushlstring(L, (char *) r->headers_out.content_type.data,
                        r->headers_out.content_type.len);
        lua_rawset(L, -3);
    }

    if (r->headers_out.content_length == NULL
        && r->headers_out.content_length_n >= 0)
    {
        lua_pushliteral(L, "content-length");
        lua_pushfstring(L, "%d", (int) r->headers_out.content_length_n);
        lua_rawset(L, -3);
    }

    lua_pushliteral(L, "connection");
    if (r->headers_out.status == NGX_HTTP_SWITCHING_PROTOCOLS) {
        lua_pushliteral(L, "upgrade");

    } else if (r->keepalive) {
        lua_pushliteral(L, "keep-alive");

    } else {
        lua_pushliteral(L, "close");
    }
    lua_rawset(L, -3);

    if (r->chunked) {
        lua_pushliteral(L, "transfer-encoding");
        lua_pushliteral(L, "chunked");
        lua_rawset(L, -3);
    }
#endif

    part = &r->headers_out.headers.part;
    header = part->elts;

    for (i = 0; /* void */; i++) {

        dd("stack top: %d", lua_gettop(L));

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }

            part = part->next;
            header = part->elts;
            i = 0;
        }

        if (header[i].hash == 0) {
            continue;
        }

        if (raw) {
            lua_pushlstring(L, (char *) header[i].key.data, header[i].key.len);

        } else {
            /* nginx does not even bother initializing output header entry's
             * "lowcase_key" field. so we cannot count on that at all. */
            if (header[i].key.len > lowcase_key_sz) {
                lowcase_key_sz = header[i].key.len * 2;

                /* we allocate via Lua's GC to prevent in-request
                 * leaks in the nginx request memory pools */
                lowcase_key = lua_newuserdata(L, lowcase_key_sz);
                lua_insert(L, 1);
            }

            ngx_strlow(lowcase_key, header[i].key.data, header[i].key.len);
            lua_pushlstring(L, (char *) lowcase_key, header[i].key.len);
        }

        /* stack: [udata] table key */

        lua_pushlstring(L, (char *) header[i].value.data,
                        header[i].value.len); /* stack: [udata] table key
                                                 value */

        ngx_http_lua_set_multi_value_table(L, -3);

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua response header: \"%V: %V\"",
                       &header[i].key, &header[i].value);

        if (--count == 0) {
            return 1;
        }
    }

    return 1;
}
Esempio n. 7
0
void NativeInterface::managedPointerReleased(void *entry, int version)
{
    lua_State **_L = handleEntryToLuaState.get(entry);

    if (!_L)
    {
        return;
    }

    lua_State *L = *_L;

    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDVERSION);

    lua_pushlightuserdata(L, entry);
    lua_pushnil(L);
    lua_settable(L, -3);

    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDUSERDATA);
    lua_rawgeti(L, LUA_GLOBALSINDEX, LSINDEXMANAGEDNATIVESCRIPT);

    lua_pushlightuserdata(L, entry);
    lua_gettable(L, -3); // get from userdata
    if (!lua_isnil(L, -1))
    {
        lua_pushvalue(L, -1);
        lua_gettable(L, -3);

        assert(lua_istable(L, -1));

        // clear the instance table of any values
        // this will force the deleted managed metatable
        // to trip on access (once set below)
        int tidx = lua_gettop(L);

        lua_newtable(L);

        int clearTableIdx  = tidx + 1;
        int numClearValues = 0;

        lua_pushnil(L); /* first key */

        while (lua_next(L, tidx) != 0)
        {
            if (lua_isnumber(L, -2))
            {
                // We want to keep basic info in the (deleted) instance
                int indexer = (int)lua_tonumber(L, -2);

                if ((indexer == LSINDEXNATIVE) || (indexer == LSINDEXTYPE))
                {
                    lua_pop(L, 1); // pop value
                    continue;
                }
            }

            // push the key
            lua_pushvalue(L, -2);
            lua_rawseti(L, clearTableIdx, numClearValues++);

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

        // now run through the clearTable which holds the instance keys as values
        // and null out the instance keys

        for (int i = 0; i < numClearValues; i++)
        {
            lua_rawgeti(L, clearTableIdx, i);
            lua_pushnil(L);
            lua_settable(L, tidx);
        }

        lua_settop(L, tidx);

        lua_pushboolean(L, 1);
        lua_rawseti(L, tidx, LSINDEXDELETEDMANAGED);

        // mark managed instance as deleted
        // this replaces the metatable of the instance
        // with the deleted managed metatable which
        // provides errors on access
        luaL_getmetatable(L, LSDELETEDMANAGED);
        lua_setmetatable(L, -2);
        lua_pop(L, 1);

        lua_pushnil(L);
        lua_settable(L, -3); // clear from script
    }

    lua_pop(L, 1);
    // pop managed script

    lua_pushlightuserdata(L, entry);
    lua_pushnil(L);
    lua_settable(L, -3);

    lua_pop(L, 2);
}
Esempio n. 8
0
static int lua_co_tcp(lua_State *L)
{
    cosocket_t *c*k = (cosocket_t *) lua_newuserdata(L, sizeof(cosocket_t));

    if(!c*k) {
        lua_pushnil(L);
        lua_pushstring(L, "stack error!");
        return 2;
    }

    bzero(c*k, sizeof(cosocket_t));

    if(lua_isstring(L, 1) && lua_isstring(L, 2)) {
        if(c*k->ctx) {
            SSL_CTX_free(c*k->ctx);
        }

        c*k->ctx = SSL_CTX_new(SSLv23_client_method());

        if(c*k->ctx == NULL) {
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_new Error");
            return 2;
        }

        if(lua_isstring(L, 3)) {
            if(c*k->ssl_pw) {
                free(c*k->ssl_pw);
            }

            size_t len = 0;
            const char *p1 = lua_tolstring(L, 3, &len);
            c*k->ssl_pw = malloc(len + 1);

            if(c*k->ssl_pw) {
                memcpy(c*k->ssl_pw, p1, len);
                c*k->ssl_pw[len] = '\0';
                SSL_CTX_set_default_passwd_cb_userdata(c*k->ctx, (void *)c*k->ssl_pw);
                SSL_CTX_set_default_passwd_cb(c*k->ctx, ssl_password_cb);
            }

            int l = snprintf(temp_buf, 4096, "%s:%s:%s", lua_tostring(L, 1), lua_tostring(L, 2), p1);
            c*k->ssl_sign = fnv1a_32(temp_buf, l);

        } else {
            int l = snprintf(temp_buf, 4096, "%s:%s:", lua_tostring(L, 1), lua_tostring(L, 2));
            c*k->ssl_sign = fnv1a_32(temp_buf, l);
        }

        if(SSL_CTX_use_certificate_file(c*k->ctx, lua_tostring(L, 1), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_use_certificate_file Error");
            return 2;
        }

        if(SSL_CTX_use_PrivateKey_file(c*k->ctx, lua_tostring(L, 2), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_use_PrivateKey_file Error");
            return 2;
        }

        if(!SSL_CTX_check_private_key(c*k->ctx)) {
            SSL_CTX_free(c*k->ctx);
            c*k->ctx = NULL;
            lua_pushnil(c*k->L);
            lua_pushstring(c*k->L, "SSL_CTX_check_private_key Error");
            return 2;
        }

        c*k->use_ssl = 1;

    } else if(lua_isboolean(L, 1) && lua_toboolean(L, 1) == 1) {
        c*k->use_ssl = 1;

    } else {
        c*k->use_ssl = 0;
    }

    c*k->L = L;
    c*k->fd = -1;
    c*k->timeout = 30000;
    /*
    if(luaL_newmetatable(L, "cosocket")) {
        //luaL_checkstack(L, 1, "not enough stack to register connection MT");
        lua_pushvalue(L, lua_upvalueindex(1));
        setfuncs(L, M, 1);
        lua_pushvalue(L, -1);
        lua_setfield(L, -2, "__index");
    }*/
    luaL_getmetatable(L, "cosocket:tcp");
    lua_setmetatable(L, -2);

    return 1;
}
static int
ngx_http_lua_socket_udp_setpeername(lua_State *L)
{
    ngx_http_request_t          *r;
    ngx_http_lua_ctx_t          *ctx;
    ngx_str_t                    host;
    int                          port;
    ngx_resolver_ctx_t          *rctx, temp;
    ngx_http_core_loc_conf_t    *clcf;
    int                          saved_top;
    int                          n;
    u_char                      *p;
    size_t                       len;
    ngx_url_t                    url;
    ngx_int_t                    rc;
    ngx_http_lua_loc_conf_t     *llcf;
    ngx_udp_connection_t        *uc;
    int                          timeout;

    ngx_http_lua_socket_udp_upstream_t      *u;

    n = lua_gettop(L);
    if (n != 2 && n != 3) {
        return luaL_error(L, "ngx.socket.udp setpeername: expecting 2 or 3 "
                          "arguments (including the object), but seen %d", n);
    }

    lua_pushlightuserdata(L, &ngx_http_lua_request_key);
    lua_rawget(L, LUA_GLOBALSINDEX);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (r == NULL) {
        return luaL_error(L, "no request found");
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
    if (ctx == NULL) {
        return luaL_error(L, "no ctx found");
    }

    ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE
                               | NGX_HTTP_LUA_CONTEXT_ACCESS
                               | NGX_HTTP_LUA_CONTEXT_CONTENT);

    luaL_checktype(L, 1, LUA_TTABLE);

    p = (u_char *) luaL_checklstring(L, 2, &len);

    host.data = ngx_palloc(r->pool, len + 1);
    if (host.data == NULL) {
        return luaL_error(L, "out of memory");
    }

    host.len = len;

    ngx_memcpy(host.data, p, len);
    host.data[len] = '\0';

    if (n == 3) {
        port = luaL_checkinteger(L, 3);

        if (port < 0 || port > 65536) {
            lua_pushnil(L);
            lua_pushfstring(L, "bad port number: %d", port);
            return 2;
        }

    } else { /* n == 2 */
        port = 0;
    }

    lua_rawgeti(L, 1, SOCKET_CTX_INDEX);
    u = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (u) {
        if (u->waiting) {
            lua_pushnil(L);
            lua_pushliteral(L, "socket busy");
            return 2;
        }

        if (u->udp_connection.connection) {
            ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "lua udp socket reconnect without shutting down");

            ngx_http_lua_socket_udp_finalize(r, u);
        }

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua reuse socket upstream ctx");

    } else {
        u = lua_newuserdata(L, sizeof(ngx_http_lua_socket_udp_upstream_t));
        if (u == NULL) {
            return luaL_error(L, "out of memory");
        }

#if 1
        lua_createtable(L, 0 /* narr */, 1 /* nrec */); /* metatable */
        lua_pushcfunction(L, ngx_http_lua_socket_udp_upstream_destroy);
        lua_setfield(L, -2, "__gc");
        lua_setmetatable(L, -2);
#endif

        lua_rawseti(L, 1, SOCKET_CTX_INDEX);
    }

    ngx_memzero(u, sizeof(ngx_http_lua_socket_udp_upstream_t));

    u->request = r; /* set the controlling request */
    llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module);

    u->conf = llcf;

    uc = &u->udp_connection;

    uc->log = *r->connection->log;

    dd("lua peer connection log: %p", &uc->log);

    lua_rawgeti(L, 1, SOCKET_TIMEOUT_INDEX);
    timeout = (ngx_int_t) lua_tointeger(L, -1);
    lua_pop(L, 1);

    if (timeout > 0) {
        u->read_timeout = (ngx_msec_t) timeout;

    } else {
        u->read_timeout = u->conf->read_timeout;
    }

    ngx_memzero(&url, sizeof(ngx_url_t));

    url.url.len = host.len;
    url.url.data = host.data;
    url.default_port = port;
    url.no_resolve = 1;

    if (ngx_parse_url(r->pool, &url) != NGX_OK) {
        lua_pushnil(L);

        if (url.err) {
            lua_pushfstring(L, "failed to parse host name \"%s\": %s",
                            host.data, url.err);

        } else {
            lua_pushfstring(L, "failed to parse host name \"%s\"", host.data);
        }

        return 2;
    }

    u->resolved = ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_resolved_t));
    if (u->resolved == NULL) {
        return luaL_error(L, "out of memory");
    }

    if (url.addrs && url.addrs[0].sockaddr) {
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua udp socket network address given directly");

        u->resolved->sockaddr = url.addrs[0].sockaddr;
        u->resolved->socklen = url.addrs[0].socklen;
        u->resolved->naddrs = 1;
        u->resolved->host = url.addrs[0].name;

    } else {
        u->resolved->host = host;
        u->resolved->port = (in_port_t) port;
    }

    if (u->resolved->sockaddr) {
        rc = ngx_http_lua_socket_resolve_retval_handler(r, u, L);
        if (rc == NGX_AGAIN) {
            return lua_yield(L, 0);
        }

        return rc;
    }

    clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

    temp.name = host;
    rctx = ngx_resolve_start(clcf->resolver, &temp);
    if (rctx == NULL) {
        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;
        lua_pushnil(L);
        lua_pushliteral(L, "failed to start the resolver");
        return 2;
    }

    if (rctx == NGX_NO_RESOLVER) {
        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;
        lua_pushnil(L);
        lua_pushfstring(L, "no resolver defined to resolve \"%s\"", host.data);
        return 2;
    }

    rctx->name = host;
    rctx->type = NGX_RESOLVE_A;
    rctx->handler = ngx_http_lua_socket_resolve_handler;
    rctx->data = u;
    rctx->timeout = clcf->resolver_timeout;

    u->resolved->ctx = rctx;

    saved_top = lua_gettop(L);

    if (ngx_resolve_name(rctx) != NGX_OK) {
        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua udp socket fail to run resolver immediately");

        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_RESOLVER;

        u->resolved->ctx = NULL;
        lua_pushnil(L);
        lua_pushfstring(L, "%s could not be resolved", host.data);

        return 2;
    }

    if (u->waiting == 1) {
        /* resolved and already connecting */
        return lua_yield(L, 0);
    }

    n = lua_gettop(L) - saved_top;
    if (n) {
        /* errors occurred during resolving or connecting
         * or already connected */
        return n;
    }

    /* still resolving */

    u->waiting = 1;
    u->prepare_retvals = ngx_http_lua_socket_resolve_retval_handler;

    ctx->data = u;
    ctx->udp_socket_busy = 1;
    ctx->udp_socket_ready = 0;

    if (ctx->entered_content_phase) {
        r->write_event_handler = ngx_http_lua_content_wev_handler;
    }

    return lua_yield(L, 0);
}
Esempio n. 10
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);
}
Esempio n. 11
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.
}
Esempio n. 12
0
void ScriptController::executeFunctionHelper(int resultCount, const char* func, const char* args, va_list* list)
{
    if (func == NULL)
    {
        GP_ERROR("Lua function name must be non-null.");
        return;
    }

    const char* sig = args;

    int argumentCount = 0;
    lua_getglobal(_lua, func);

    // Push the arguments to the Lua stack if there are any.
    if (sig)
    {
        while (true)
        {
            if (!(*sig))
                break;

            switch(*sig++)
            {
            // Signed integers.
            case 'c':
            case 'h':
            case 'i':
            case 'l':
                lua_pushinteger(_lua, va_arg(*list, int));
                break;
            // Unsigned integers.
            case 'u':
                // Skip past the actual type (long, int, short, char).
                sig++;
                lua_pushunsigned(_lua, va_arg(*list, int));
                break;
            // Booleans.
            case 'b':
                lua_pushboolean(_lua, va_arg(*list, int));
                break;
            // Floating point numbers.
            case 'f':
            case 'd':
                lua_pushnumber(_lua, va_arg(*list, double));
                break;
            // Strings.
            case 's':
                lua_pushstring(_lua, va_arg(*list, char*));
                break;
            // Pointers.
            case 'p':
                lua_pushlightuserdata(_lua, va_arg(*list, void*));
                break;
            // Enums.
            case '[':
            {
                std::string type = sig;
                type = type.substr(0, type.find("]"));

                // Skip past the closing ']' (the semi-colon here is intentional-do not remove).
                while (*sig++ != ']');

                unsigned int value = va_arg(*list, int);
                std::string enumStr = "";
                for (unsigned int i = 0; enumStr.size() == 0 && i < _stringFromEnum.size(); i++)
                {
                    enumStr = (*_stringFromEnum[i])(type, value);
                }

                lua_pushstring(_lua, enumStr.c_str());
                break;
            }
            // Object references/pointers (Lua userdata).
            case '<':
            {
                std::string type = sig;
                type = type.substr(0, type.find(">"));

                // Skip past the closing '>' (the semi-colon here is intentional-do not remove).
                while (*sig++ != '>');

                // Calculate the unique Lua type name.
                size_t i = type.find("::");
                while (i != std::string::npos)
                {
                    // We use "" as the replacement here-this must match the preprocessor
                    // define SCOPE_REPLACEMENT from the gameplay-luagen project.
                    type.replace(i, 2, "");
                    i = type.find("::");
                }

                void* ptr = va_arg(*list, void*);
                if (ptr == NULL)
                {
                    lua_pushnil(_lua);
                }
                else
                {
                    ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(_lua, sizeof(ScriptUtil::LuaObject));
                    object->instance = ptr;
                    object->owns = false;
                    luaL_getmetatable(_lua, type.c_str());
                    lua_setmetatable(_lua, -2);
                }
                break;
            }
            default:
                GP_ERROR("Invalid argument type '%d'.", *(sig - 1));
                break;
            }

            argumentCount++;
            luaL_checkstack(_lua, 1, "Too many arguments.");
        }
    }

    // Perform the function call.
    if (lua_pcall(_lua, argumentCount, resultCount, 0) != 0)
        GP_WARN("Failed to call function '%s' with error '%s'.", func, lua_tostring(_lua, -1));
}
Esempio n. 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;
}
Esempio n. 14
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" );
}
Esempio n. 15
0
File: ldev.c Progetto: mythay/ldev
static int ldev_serial (lua_State *L) {
    LDEV_HANDLE_t *p = NULL;
    SERIALPORT_FD_OPT opt={0};
    const char* fpath = NULL;
    
    luaL_checktype(L, 1, LUA_TSTRING); // first argument must be a serial port path
    luaL_checktype(L, 2, LUA_TTABLE); // second argument must be a table contains the serial  port configuration
    lua_settop(L, 2);

    fpath = lua_tostring(L,1);

    opt.baudRate = getfield(L,"baud",115200);
    opt.dataBits= getfield(L,"bits",8);
    opt.stopBits= getfield(L,"stop",1);
    
    lua_getfield(L, -1, "parity");
    if(lua_isstring(L,-1))
    {
        const char* parity_s = lua_tostring(L,-1);
        switch(*parity_s)
        {
            case 'e':
            case 'E':
                opt.parity = SERIALPORT_PARITY_EVEN;
                break;
            case 'o':
            case 'O':
                opt.parity = SERIALPORT_PARITY_ODD;
                break;
            case 'n':
            case 'N':
                opt.parity = SERIALPORT_PARITY_NONE;
                break;
            default:
                return luaL_error(L, "invalid parity string " LUA_QS " ", parity_s);
        }
    }else
    {
        opt.parity = SERIALPORT_PARITY_NONE;
    }
    lua_pop(L, 1);

    p = (LDEV_HANDLE_t *)lua_newuserdata(L, sizeof(LDEV_HANDLE_t));
    memset(p, 0, sizeof(LDEV_HANDLE_t));
    luaL_getmetatable(L, LUA_DEVHANDLE);
    lua_setmetatable(L, -2);


    p->fd = ldev_serial_open(fpath, &opt);
    if(p->fd <= 0)
    {   
        lua_settop(L,0);
        lua_pushnil(L);
        lua_pushstring(L, "open serial fail.");
        return 2;
    }
    p->type = "serial";
    lua_replace(L,1);
    lua_settop(L,1);
    return 1;
}
Esempio n. 16
0
int
main(int argc, char **argv)
{
	int	ch;
	const char	*scriptpath = "/tmp/test.lua";

	log_init(-1);

	log_debug("debug: filter-lua: args: %s", argv[1]);
	while ((ch = getopt(argc, argv, "")) != -1) {
		switch (ch) {
		default:
			log_warnx("warn: filter-lua: bad option");
			return (1);
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	log_debug("debug: filter-lua: starting...");

	if ((L = luaL_newstate()) == NULL) {
		log_warnx("warn: filter-lua: can't create lua state");
		return (1);
	}
	luaL_openlibs(L);
	luaL_newlib(L, l_filter);
	luaL_newmetatable(L, "filter");
	lua_setmetatable(L, -2);

	lua_pushnumber(L, FILTER_OK);
	lua_setfield(L, -2, "FILTER_OK");
	lua_pushnumber(L, FILTER_FAIL);
	lua_setfield(L, -2, "FILTER_FAIL");
	lua_pushnumber(L, FILTER_CLOSE);
	lua_setfield(L, -2, "FILTER_CLOSE");

	lua_setglobal(L, "filter");

	if (luaL_loadfile(L, scriptpath) != 0) {
		log_warnx("warn: filter-lua: error loading script: %s", scriptpath);
		return (1);
	}

	if (lua_pcall(L, 0, 0, 0)) {
		log_warnx("warn: filter-lua: error running script: %s", scriptpath);
		return (1);
	}

	lua_getglobal(L, "on_connect");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_connect is present");
		filter_api_on_connect(on_connect);
	}
	lua_getglobal(L, "on_helo");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_helo is present");
		filter_api_on_helo(on_helo);
	}
	lua_getglobal(L, "on_mail");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_mail is present");
		filter_api_on_mail(on_mail);
	}
	lua_getglobal(L, "on_rcpt");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_rcpt is present");
		filter_api_on_rcpt(on_rcpt);
	}
	lua_getglobal(L, "on_data");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_data is present");
		filter_api_on_data(on_data);
	}
	lua_getglobal(L, "on_eom");
	if (lua_isfunction(L, 1)) {
		log_debug("debug: filter-lua: on_eom is present");
		filter_api_on_eom(on_eom);
	}

	filter_api_loop();

	log_debug("debug: filter-lua: exiting");

	return (0);
}
static int
ngx_http_lua_ngx_req_get_headers(lua_State *L)
{
    ngx_list_part_t              *part;
    ngx_table_elt_t              *header;
    ngx_http_request_t           *r;
    ngx_uint_t                    i;
    int                           n;
    int                           max;
    int                           raw = 0;
    int                           count = 0;

    n = lua_gettop(L);

    if (n >= 1) {
        if (lua_isnil(L, 1)) {
            max = NGX_HTTP_LUA_MAX_HEADERS;

        } else {
            max = luaL_checkinteger(L, 1);
        }

        if (n >= 2) {
            raw = lua_toboolean(L, 2);
        }

    } else {
        max = NGX_HTTP_LUA_MAX_HEADERS;
    }

    r = ngx_http_lua_get_req(L);
    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    ngx_http_lua_check_fake_request(L, r);

    part = &r->headers_in.headers.part;
    count = part->nelts;
    while (part->next) {
        part = part->next;
        count += part->nelts;
    }

    if (max > 0 && count > max) {
        count = max;
        ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua exceeding request header limit %d", max);
    }

    lua_createtable(L, 0, count);

    if (!raw) {
        lua_pushlightuserdata(L, &ngx_http_lua_headers_metatable_key);
        lua_rawget(L, LUA_REGISTRYINDEX);
        lua_setmetatable(L, -2);
    }

    part = &r->headers_in.headers.part;
    header = part->elts;

    for (i = 0; /* void */; i++) {

        dd("stack top: %d", lua_gettop(L));

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }

            part = part->next;
            header = part->elts;
            i = 0;
        }

        if (raw) {
            lua_pushlstring(L, (char *) header[i].key.data, header[i].key.len);

        } else {
            lua_pushlstring(L, (char *) header[i].lowcase_key,
                            header[i].key.len);
        }

        /* stack: table key */

        lua_pushlstring(L, (char *) header[i].value.data,
                        header[i].value.len); /* stack: table key value */

        ngx_http_lua_set_multi_value_table(L, -3);

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "lua request header: \"%V: %V\"",
                       &header[i].key, &header[i].value);

        if (--count == 0) {
            return 1;
        }
    }

    return 1;
}
Esempio n. 18
0
static int lua_carray_new(lua_State *L) {
  const char *type = luaL_optstring(L, 1, "double");

  int size;
  bool istable = lua_istable(L, 2);
  if (istable) {
#if LUA_VERSION_NUM == 502
    size = lua_rawlen(L, 2);
#else
    size = lua_objlen(L, 2);
#endif
  }
  else {
    size = luaL_optinteger(L, 2, 1);
  }
  structCArray *ud = (structCArray *)lua_newuserdata(L, sizeof(structCArray));

  ud->size = size;
  ud->type = type[0];
  ud->own = 1;

  int i;
  unsigned char *p_uchar;
  char *p_char;
  short *p_short;
  int *p_int;
  unsigned int *p_uint;
  float *p_float;
  double *p_double;

  switch (ud->type) {
  case 'b':
    p_uchar = new unsigned char[size];
    ud->ptr = p_uchar;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	// Lua stack: table, userdata, index (top)
	lua_gettable(L, -3);
	p_uchar[i] = lua_tointeger(L, -1);
	lua_pop(L, 1);
      }
    }
    break;
  case 'c':
    p_char = new char[size];
    ud->ptr = p_char;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_char[i] = lua_tointeger(L, -2);
	lua_pop(L, 1);
      }
    }
    break;
  case 's':
    p_short = new short[size];
    ud->ptr = p_short;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_short[i] = lua_tointeger(L, -2);
	lua_pop(L, 1);
      }
    }
    break;
  case 'i':
    p_int = new int[size];
    ud->ptr = p_int;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_int[i] = lua_tointeger(L, -2);
	lua_pop(L, 1);
      }
    }
    break;
  case 'u':
    p_uint = new unsigned int[size];
    ud->ptr = p_uint;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_uint[i] = lua_tointeger(L, -2);
	lua_pop(L, 1);
      }
    }
    break;
  case 'f':
    p_float = new float[size];
    ud->ptr = p_float;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_float[i] = lua_tonumber(L, -1);
	lua_pop(L, 1);
      }
    }
    break;
  case 'd':
    p_double = new double[size];
    ud->ptr = p_double;
    if (istable) {
      for (i = 0; i < size; i++) {
	lua_pushinteger(L, i+1);
	lua_gettable(L, -3);
	p_double[i] = lua_tonumber(L, -1);
	lua_pop(L, 1);
      }
    }
    break;
  default:
    ud->ptr = new char[size];
  }

  luaL_getmetatable(L, "carray_mt");
  lua_setmetatable(L, -2);
  return 1;
}
Esempio n. 19
0
int
luaopen_testlib_profile(lua_State *L) {
	// #ifdef DEBUG_LOG
	// printf("%s\n", __FUNCTION__);
	// #endif
	luaL_checkversion(L);
	luaL_Reg l[] = {
		{ "start", lstart },
		{ "stop", lstop },
		{ "resume", lresume },
		{ "yield", lyield },
		{ "resume_co", lresume_co },
		{ "yield_co", lyield_co },
		{ NULL, NULL },
	};
	luaL_newlibtable(L,l);
	lua_newtable(L);	// table thread->start time
	lua_newtable(L);	// table thread->total time

	lua_newtable(L);	// weak table
	lua_pushliteral(L, "kv"); // 同lua_pushstring,复制一个string
	lua_setfield(L, -2, "__mode"); // -2指向的weak table,key:__mode, value:栈顶, weak_table[__mode] = kv, pop出value

	lua_pushvalue(L, -1); // 复制一个weak table引用在栈顶
	lua_setmetatable(L, -3); // pop出上面复制的weak table,设置为total time table的metatable
	lua_setmetatable(L, -3); // pop出第一个weak table,设置为start time table的metatable

	lua_pushnil(L);	// cfunction (coroutine.resume or coroutine.yield), 留出位置给下面设置lua自己的协程函数
	luaL_setfuncs(L,l,3); // 所有函数共享3个upvalues,这里调用完毕会pop出上面三个value

	int libtable = lua_gettop(L); // libtable的index栈位置

	lua_getglobal(L, "coroutine");
	lua_getfield(L, -1, "resume"); // coroutine table里的resume key对应的value压顶

	lua_CFunction co_resume = lua_tocfunction(L, -1); // 取出lua自己的resume的c函数
	if (co_resume == NULL)
		return luaL_error(L, "Can't get coroutine.resume");
	lua_pop(L,1);

	lua_getfield(L, libtable, "resume"); // libtable里的resume key对应的函数压顶
	lua_pushcfunction(L, co_resume); // lua自己的resume函数压顶
	lua_setupvalue(L, -2, 3); // -2指向的闭包,该闭包的第3个upvalue,设置为栈顶的lua自己的resume函数,pop出栈顶
	lua_pop(L,1); // pop出resume闭包

	lua_getfield(L, libtable, "resume_co");
	lua_pushcfunction(L, co_resume);
	lua_setupvalue(L, -2, 3);
	lua_pop(L,1);

	lua_getfield(L, -1, "yield");

	lua_CFunction co_yield = lua_tocfunction(L, -1); // 取出lua自己的yield c函数
	if (co_yield == NULL)
		return luaL_error(L, "Can't get coroutine.yield");
	lua_pop(L,1);

	lua_getfield(L, libtable, "yield");
	lua_pushcfunction(L, co_yield);
	lua_setupvalue(L, -2, 3);
	lua_pop(L,1);

	lua_getfield(L, libtable, "yield_co");
	lua_pushcfunction(L, co_yield);
	lua_setupvalue(L, -2, 3);
	lua_pop(L,1);

	lua_settop(L, libtable);

	return 1;
}
Esempio n. 20
0
COMPAT53_API void luaL_setmetatable (lua_State *L, const char *tname) {
  luaL_checkstack(L, 1, "not enough stack slots");
  luaL_getmetatable(L, tname);
  lua_setmetatable(L, -2);
}
Esempio n. 21
0
int Xml_eval(lua_State *L) {
	char* str = 0;
	size_t str_size=0;
	if(lua_isuserdata(L,1))
		str = (char*)lua_touserdata(L,1);
	else {
		const char * sTmp = luaL_checklstring(L,1,&str_size);
		str = (char*)malloc(str_size+1);
		memcpy(str, sTmp, str_size);
		str[str_size]=0;
	}
	Tokenizer* tok = Tokenizer_new(str, str_size ? str_size : strlen(str));
	lua_settop(L,0);
	const char* token=0;
	int firstStatement = 1;
	while((token=Tokenizer_next(tok))!=0) if(token[0]==OPN) { // new tag found
		if(lua_gettop(L)) {
			int newIndex=lua_rawlen(L,-1)+1;
			lua_pushnumber(L,newIndex);
			lua_newtable(L);
			lua_settable(L, -3);
			lua_pushnumber(L,newIndex);
			lua_gettable(L,-2);
		}
		else {
			if (firstStatement) {
				lua_newtable(L);
				firstStatement = 0;
			}
			else return lua_gettop(L);
		}
		// set metatable:
		lua_newtable(L);
		lua_pushliteral(L, "__index");
		lua_getglobal(L, "xml");
		lua_settable(L, -3);

		lua_pushliteral(L, "__tostring"); // set __tostring metamethod
		lua_getglobal(L, "xml");
		lua_pushliteral(L,"str");
		lua_gettable(L, -2);
		lua_remove(L, -2);
		lua_settable(L, -3);
		lua_setmetatable(L, -2);

		// parse tag and content:
		lua_pushnumber(L,0); // use index 0 for storing the tag
		lua_pushstring(L, Tokenizer_next(tok));
		lua_settable(L, -3);

		while(((token = Tokenizer_next(tok))!=0)&&(token[0]!=CLS)&&(token[0]!=ESC)) { // parse tag header
			size_t sepPos=find(token, "=", 0);
			if(token[sepPos]) { // regular attribute
				const char* aVal =token+sepPos+2;
				lua_pushlstring(L, token, sepPos);
				size_t lenVal = strlen(aVal)-1;
				if(!lenVal) Xml_pushDecode(L, "", 0);
				else Xml_pushDecode(L, aVal, lenVal);
				lua_settable(L, -3);
			}
		}
		if(!token||(token[0]==ESC)) {
			if(lua_gettop(L)>1) lua_settop(L,-2); // this tag has no content, only attributes
			else break;
		}
	}
	else if(token[0]==ESC) { // previous tag is over
		if(lua_gettop(L)>1) lua_settop(L,-2); // pop current table
		else break;
	}
	else { // read elements
		lua_pushnumber(L,lua_rawlen(L,-1)+1);
		Xml_pushDecode(L, token, 0);
		lua_settable(L, -3);
	}
	Tokenizer_delete(tok);
	free(str);
	return lua_gettop(L);
}
Esempio n. 22
0
int scene_f_mesh_cmd(lua_State *L)
{
	GRLUA_DEBUG_CALL;

	scene_node_ud *data = (scene_node_ud*)lua_newuserdata(L, sizeof(scene_node_ud));
	data->node = 0;

	const char* name = luaL_checkstring(L, 1);

	std::vector<Point3D> verts;
	std::vector<Point2D> uvs;
	std::vector<Vector3D> normals;
	std::vector<std::vector<int> > face_v;
	std::vector<std::vector<int> > face_uv;
	std::vector<std::vector<int> > face_norms;

	luaL_checktype(L, 2, LUA_TTABLE);
	int vert_count = luaL_getn(L, 2);

	luaL_argcheck(L, vert_count >= 1, 2, "Tuple of vertices expected");

	for (int i = 1; i <= vert_count; i++)
	{
		lua_rawgeti(L, 2, i);

		Point3D vertex;
		get_tuple(L, -1, &vertex[0], 3);
		verts.push_back(vertex);
		lua_pop(L, 1);
	}

	luaL_checktype(L, 3, LUA_TTABLE);
	int uv_count = luaL_getn(L, 3);

	for (int i = 1; i <= uv_count; ++i)
	{
		lua_rawgeti(L, 3, i);

		Point2D uv;
		get_tuple(L, -1, &uv[0], 2);
		uv[1] = 1-uv[1];
		uvs.push_back(uv);
		lua_pop(L, 1);
	}

	luaL_checktype(L, 4, LUA_TTABLE);
	int norm_count = luaL_getn(L, 4);

	for (int i = 1; i <= norm_count; ++i)
	{
		lua_rawgeti(L, 4, i);

		Vector3D norm;
		get_tuple(L, -1, &norm[0], 3);
		norm.normalize();
		normals.push_back(norm);
		lua_pop(L, 1);
	}

	luaL_checktype(L, 5, LUA_TTABLE);
	int face_count = luaL_getn(L, 5);

	luaL_argcheck(L, face_count >= 1, 5, "Tuple of faces expected");

	face_v.resize(face_count);
	face_uv.resize(face_count);
	face_norms.resize(face_count);

	for (int i = 1; i <= face_count; ++i)
	{
		lua_rawgeti(L, 5, i);

		luaL_checktype(L, -1, LUA_TTABLE);
		int attrib_count = luaL_getn(L, -1);

		luaL_argcheck(L, attrib_count >= 1, 5, "Vertices expected.");

		// Get the vertices
		lua_rawgeti(L, -1, 1);
		int index_count = luaL_getn(L, -1);
		luaL_argcheck(L, index_count >= 3, 5, "Tuple of indices expected");
		face_v[i-1].resize(index_count);
		get_tuple(L, -1, &face_v[i-1][0], index_count);
		lua_pop(L, 1);

		if (attrib_count >= 2)
		{
			lua_rawgeti(L, -1, 2);
			index_count = luaL_getn(L, -1);
			face_uv[i-1].resize(index_count);
			get_tuple(L, -1, &face_uv[i-1][0], index_count);
			lua_pop(L, 1);
		}

		if (attrib_count >= 3)
		{
			lua_rawgeti(L, -1, 3);
			index_count = luaL_getn(L, -1);
			face_norms[i-1].resize(index_count);
			get_tuple(L, -1, &face_norms[i-1][0], index_count);
			lua_pop(L, 1);
		}

		lua_pop(L, 1);
	}

	Mesh *mesh = new Mesh(verts, uvs, normals,
			face_v, face_uv, face_norms);
	GRLUA_DEBUG(*mesh);
	data->node = new GeometryNode(name, mesh);

	luaL_getmetatable(L, SCENE_META);
	lua_setmetatable(L, -2);

	return 1;
}
Esempio n. 23
0
/* Class index function
    * If the object is a userdata (ie, an object), it searches the field in
    * the alternative table stored in the corresponding "ubox" table.
*/
static int class_index_event (lua_State* L)
{
    int t = lua_type(L,1);
    if (t == LUA_TUSERDATA)
    {
        /* Access alternative table */
#ifdef LUA_VERSION_NUM /* new macro on version 5.1 */
        lua_getfenv(L,1);
        if (!lua_rawequal(L, -1, TOLUA_NOPEER)) {
            lua_pushvalue(L, 2); /* key */
            lua_gettable(L, -2); /* on lua 5.1, we trade the "tolua_peers" lookup for a gettable call */
            if (!lua_isnil(L, -1))
                return 1;
        };
#else
        lua_pushstring(L,"tolua_peers");
        lua_rawget(L,LUA_REGISTRYINDEX);        /* stack: obj key ubox */
        lua_pushvalue(L,1);
        lua_rawget(L,-2);                       /* stack: obj key ubox ubox[u] */
        if (lua_istable(L,-1))
        {
            lua_pushvalue(L,2);  /* key */
            lua_rawget(L,-2);                      /* stack: obj key ubox ubox[u] value */
            if (!lua_isnil(L,-1))
                return 1;
        }
#endif
        lua_settop(L,2);                        /* stack: obj key */
        /* Try metatables */
        lua_pushvalue(L,1);                     /* stack: obj key obj */
        while (lua_getmetatable(L,-1))
        {   /* stack: obj key obj mt */
            lua_remove(L,-2);                      /* stack: obj key mt */
            if (lua_isnumber(L,2))                 /* check if key is a numeric value */
            {
                /* try operator[] */
                lua_pushstring(L,".geti");
                lua_rawget(L,-2);                      /* stack: obj key mt func */
                if (lua_isfunction(L,-1))
                {
                    lua_pushvalue(L,1);
                    lua_pushvalue(L,2);
                    lua_call(L,2,1);
                    return 1;
                }
            }
            else
            {
                lua_pushvalue(L,2);                    /* stack: obj key mt key */
                lua_rawget(L,-2);                      /* stack: obj key mt value */
                if (!lua_isnil(L,-1))
                    return 1;
                else
                    lua_pop(L,1);
                /* try C/C++ variable */
                lua_pushstring(L,".get");
                lua_rawget(L,-2);                      /* stack: obj key mt tget */
                if (lua_istable(L,-1))
                {
                    lua_pushvalue(L,2);
                    lua_rawget(L,-2);                      /* stack: obj key mt value */
                    if (lua_iscfunction(L,-1))
                    {
                        lua_pushvalue(L,1);
                        lua_pushvalue(L,2);
                        lua_call(L,2,1);
                        return 1;
                    }
                    else if (lua_istable(L,-1))
                    {
                        /* deal with array: create table to be returned and cache it in ubox */
                        void* u = *((void**)lua_touserdata(L,1));
                        lua_newtable(L);                /* stack: obj key mt value table */
                        lua_pushstring(L,".self");
                        lua_pushlightuserdata(L,u);
                        lua_rawset(L,-3);               /* store usertype in ".self" */
                        lua_insert(L,-2);               /* stack: obj key mt table value */
                        lua_setmetatable(L,-2);         /* set stored value as metatable */
                        lua_pushvalue(L,-1);            /* stack: obj key met table table */
                        lua_pushvalue(L,2);             /* stack: obj key mt table table key */
                        lua_insert(L,-2);               /*  stack: obj key mt table key table */
                        storeatubox(L,1);               /* stack: obj key mt table */
                        return 1;
                    }
                }
            }
            lua_settop(L,3);
        }
        lua_pushnil(L);
        return 1;
    }
    else if (t== LUA_TTABLE)
    {
        lua_pushvalue(L,1);
        class_table_get_index(L);
        return 1;
    }
    lua_pushnil(L);
    return 1;
}
Esempio n. 24
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);

    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_ENCODE_MAX_DEPTH;
    cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
    cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
    cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
    cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
    cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;

#if DEFAULT_ENCODE_KEEP_BUFFER > 0
    strbuf_init(&cfg->encode_buf, 0);
#endif

    /* 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 */
}
/*
** Read the options specified in the ini file.
**
*/
void CMeasureScript::ReadOptions(CConfigParser& parser, const WCHAR* section)
{
	CMeasure::ReadOptions(parser, section);

	std::wstring file = parser.ReadString(section, L"ScriptFile", L"");

	if (!file.empty())
	{
		if (m_MeterWindow)
		{
			m_MeterWindow->MakePathAbsolute(file);
		}
		std::string scriptFile = ConvertToAscii(file.c_str());

		if (!m_Initialized ||
			strcmp(scriptFile.c_str(), m_ScriptFile.c_str()) != 0)
		{
			DeleteLuaScript();

			lua_State* L = LuaManager::GetState();
			m_ScriptFile = scriptFile;
			m_LuaScript = new LuaScript(m_ScriptFile.c_str());

			if (m_LuaScript->IsInitialized())
			{
				bool hasInitializeFunction = m_LuaScript->IsFunction(g_InitializeFunctionName);
				m_HasUpdateFunction = m_LuaScript->IsFunction(g_UpdateFunctionName);
				m_HasGetStringFunction = m_LuaScript->IsFunction(g_GetStringFunctionName);  // For backwards compatbility

				if (m_HasGetStringFunction)
				{
					LogWithArgs(LOG_WARNING, L"Script: Using deprecated GetStringValue() in [%s]", m_Name.c_str());
				}

				lua_rawgeti(L, LUA_GLOBALSINDEX, m_LuaScript->GetRef());

				*(CMeterWindow**)lua_newuserdata(L, sizeof(CMeterWindow*)) = m_MeterWindow;
				lua_getglobal(L, "CMeterWindow");
				lua_setmetatable(L, -2);
				lua_setfield(L, -2, "SKIN");

				*(CMeasure**)lua_newuserdata(L, sizeof(CMeasure*)) = this;
				lua_getglobal(L, "CMeasure");
				lua_setmetatable(L, -2);
				lua_setfield(L, -2, "SELF");

				// For backwards compatibility
				lua_getfield(L, -1, "PROPERTIES");
				if (lua_isnil(L, -1) == 0)
				{
					lua_pushnil(L);
					
					// Look in the table for values to read from the section
					while (lua_next(L, -2))
					{
						lua_pop(L, 1);
						const char* strKey = lua_tostring(L, -1);

						std::wstring wstrKey = ConvertToWide(strKey);
						const std::wstring& wstrValue = parser.ReadString(section, wstrKey.c_str(), L"");

						if (!wstrValue.empty())
						{
							std::string strStrVal = ConvertToAscii(wstrValue.c_str());
							const char* strValue = strStrVal.c_str();

							lua_pushstring(L, strValue);
							lua_setfield(L, -3, strKey);
						}
					}
				}

				// Pop PROPERTIES table and our table
				lua_pop(L, 2);

				if (hasInitializeFunction)
				{
					m_LuaScript->RunFunction(g_InitializeFunctionName);
				}
			}
			else
			{
				DeleteLuaScript();
			}
		}
	}
	else
	{
		LogWithArgs(LOG_ERROR, L"Script: File not valid in [%s]", m_Name.c_str());
		DeleteLuaScript();
	}
}
Esempio n. 26
0
int
get_pgfunc(lua_State *L)
{
	Lua_pgfunc *lf;
	Pgfunc_options opt;
	MemoryContext m;
	const char* reg_name = NULL;
	HeapTuple proctup;
	Form_pg_proc proc;
	int luasrc = 0;
	Oid funcid = 0;

	BEGINLUA;

	opt.only_internal = true;
	opt.throwable = true;

	if (lua_gettop(L) == 2){
		luaL_checktype(L, 2, LUA_TTABLE);
		parse_options(L, &opt);
	}else if (lua_gettop(L) != 1){
		return luaL_error(L, "pgfunc(text): wrong arguments");
	}
	if(lua_type(L, 1) == LUA_TSTRING){
		reg_name = luaL_checkstring(L, 1);
		m = MemoryContextSwitchTo(tmpcontext);
		PG_TRY();
		{
			funcid = DatumGetObjectId(DirectFunctionCall1(regprocedurein, CStringGetDatum(reg_name)));
		}
		PG_CATCH();{}
		PG_END_TRY();
		MemoryContextSwitchTo(m);
		MemoryContextReset(tmpcontext);
	}else if (lua_type(L, 1) == LUA_TNUMBER){
		funcid = luaL_checkinteger(L, 1);
	}

	if (!OidIsValid(funcid)){
		if (reg_name)
			return luaL_error(L,"failed to register %s", reg_name);
		return luaL_error(L,"failed to register function with oid %d", funcid);
	}

	proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
	if (!HeapTupleIsValid(proctup)){
		return luaL_error(L,"cache lookup failed for function %d", funcid);
	}

	proc = (Form_pg_proc) GETSTRUCT(proctup);

	luasrc = ((proc->prolang == get_pllua_oid())
		  || (proc->prolang == get_plluau_oid()));
	if ( opt.only_internal
			&&(proc->prolang != INTERNALlanguageId)
			&&(!luasrc) ){
		ReleaseSysCache(proctup);
		return luaL_error(L, "supported only SQL/internal functions");
	}


	lf = (Lua_pgfunc *)lua_newuserdata(L, sizeof(Lua_pgfunc));

	/*make it g/collected*/
	luaP_getfield(L, pg_func_type_name);
	lua_setmetatable(L, -2);


	lf->prorettype = proc->prorettype;
	lf->funcid = funcid;
	lf->options = opt;

	{
		Oid *argtypes;
		char **argnames;
		char *argmodes;
		int argc;
		MemoryContext cur = CurrentMemoryContext;

		MemoryContextSwitchTo(tmpcontext);

		argc = get_func_arg_info(proctup,
					 &argtypes, &argnames, &argmodes);

		MemoryContextSwitchTo(get_common_ctx());

		lf->numargs = argc;
		lf->argtypes = (Oid*)palloc(argc * sizeof(Oid));
		memcpy(lf->argtypes, argtypes, argc * sizeof(Oid));
		MemoryContextSwitchTo(cur);
		MemoryContextReset(tmpcontext);
	}

	if (luasrc){
		bool isnull;
		text *t;
		const char *s;
		luaL_Buffer b;
		int pcall_result;
		Datum prosrc;

		if((lf->numargs != 1)
				|| (lf->argtypes[0] != INTERNALOID)
				|| (lf->prorettype != INTERNALOID)){
			luaL_error(L, "pgfunc accepts only 'internal' pllua/u functions with internal argument");
		}

		prosrc = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosrc, &isnull);
		if (isnull) elog(ERROR, "[pgfunc]: null lua prosrc");
		luaL_buffinit(L, &b);

		luaL_addstring(&b,"do ");
		t = DatumGetTextP(prosrc);
		luaL_addlstring(&b, VARDATA(t), VARSIZE(t) - VARHDRSZ);
		luaL_addstring(&b, " end");
		luaL_pushresult(&b);
		s = lua_tostring(L, -1);

		ReleaseSysCache(proctup);
		clean_pgfuncinfo(lf);

		if (luaL_loadbuffer(L, s, strlen(s), "pgfunc chunk"))
			luaL_error(L, "compile");

		lua_remove(L, -2); /*delete source element*/

		pcall_result = lua_pcall(L, 0, 1, 0);
		lua_remove(L, -2); /*delete chunk*/
		if(pcall_result == 0){
			ENDLUAV(1);
			return 1;
		}

		if( pcall_result == LUA_ERRRUN)
			luaL_error(L,"%s %s","Runtime error:",lua_tostring(L, -1));
		else if(pcall_result == LUA_ERRMEM)
			luaL_error(L,"%s %s","Memory error:",lua_tostring(L, -1));
		else if(pcall_result == LUA_ERRERR)
			luaL_error(L,"%s %s","Error:",lua_tostring(L, -1));

		return luaL_error(L, "pgfunc unknown error");
	}

	if(proc->proretset) {
		lua_pushcclosure(L, pgfunc_rows, 1);
	} else {
		fmgr_info(funcid, &lf->fi);
		lua_pushcclosure(L, pg_callable_func, 1);
	}



	ReleaseSysCache(proctup);

	ENDLUAV(1);
	return 1;
}
Esempio n. 27
0
static int vlclua_sd_add_item( lua_State *L )
{
    services_discovery_t *p_sd = (services_discovery_t *)vlclua_get_this( L );
    if( lua_istable( L, -1 ) )
    {
        lua_getfield( L, -1, "path" );
        if( lua_isstring( L, -1 ) )
        {
            const char *psz_path = lua_tostring( L, -1 );

            lua_getfield( L, -2, "title" );
            const char *psz_title = luaL_checkstring( L, -1 ) ? luaL_checkstring( L, -1 ) : psz_path;

            /* The table must be at the top of the stack when calling
             * vlclua_read_options() */
            char **ppsz_options = NULL;
            int i_options = 0;
            lua_pushvalue( L, -3 );
            vlclua_read_options( p_sd, L, &i_options, &ppsz_options );

            input_item_t *p_input = input_item_NewExt( psz_path, psz_title,
                                                       i_options,
                                                       (const char **)ppsz_options,
                                                       VLC_INPUT_OPTION_TRUSTED, -1 );
            lua_pop( L, 3 );

            if( p_input )
            {
                vlclua_read_meta_data( p_sd, L, p_input );
                /* This one is to be tested... */
                vlclua_read_custom_meta_data( p_sd, L, p_input );
                /* The duration is given in seconds, convert to microseconds */
                lua_getfield( L, -1, "duration" );
                if( lua_isnumber( L, -1 ) )
                   input_item_SetDuration( p_input, (lua_tonumber( L, -1 )*1e6) );
                else if( !lua_isnil( L, -1 ) )
                    msg_Warn( p_sd, "Item duration should be a number (in seconds)." );
                lua_pop( L, 1 );
                lua_getfield( L, -1, "category" );
                if( lua_isstring( L, -1 ) )
                    services_discovery_AddItem( p_sd, p_input, luaL_checkstring( L, -1 ) );
                else
                    services_discovery_AddItem( p_sd, p_input, NULL );
                lua_pop( L, 1 );

                /* string to build the input item uid */
                lua_getfield( L, -1, "uiddata" );
                if( lua_isstring( L, -1 ) )
                {
                    char *s = strdup( luaL_checkstring( L, -1 ) );
                    if ( s )
                    {
                        struct md5_s md5;
                        InitMD5( &md5 );
                        AddMD5( &md5, s, strlen( s ) );
                        EndMD5( &md5 );
                        free( s );
                        s = psz_md5_hash( &md5 );
                        if ( s )
                            input_item_AddInfo( p_input, "uid", "md5", "%s", s );
                        free( s );
                    }
                }
                lua_pop( L, 1 );

                input_item_t **udata = (input_item_t **)
                                       lua_newuserdata( L, sizeof( input_item_t * ) );
                *udata = p_input;
                if( luaL_newmetatable( L, "input_item_t" ) )
                {
                    lua_newtable( L );
                    luaL_register( L, NULL, vlclua_item_reg );
                    lua_setfield( L, -2, "__index" );
                    lua_pushliteral( L, "none of your business" );
                    lua_setfield( L, -2, "__metatable" );
                }
                lua_setmetatable( L, -2 );
                vlc_gc_decref( p_input );
            }
            while( i_options > 0 )
                free( ppsz_options[--i_options] );
            free( ppsz_options );
        }
        else
            msg_Err( p_sd, "vlc.sd.add_item: the \"path\" parameter can't be empty" );
    }
    else
        msg_Err( p_sd, "Error parsing add_item arguments" );
    return 1;
}
Esempio n. 28
0
void LuaShipDef::Register()
{
	lua_State *l = Lua::manager->GetLuaState();

	LUA_DEBUG_START(l);

	lua_newtable(l);

	for (auto iter : ShipType::types)
	{
		const ShipType &st = iter.second;
		lua_newtable(l);

		pi_lua_settable(l, "id",                iter.first.c_str());
		pi_lua_settable(l, "name",              st.name.c_str());
		pi_lua_settable(l, "shipClass",         st.shipClass.c_str());
		pi_lua_settable(l, "manufacturer",      st.manufacturer.c_str());
		pi_lua_settable(l, "modelName",         st.modelName.c_str());
		pi_lua_settable(l, "cockpitName",		st.cockpitName.c_str());
		pi_lua_settable(l, "tag",               EnumStrings::GetString("ShipTypeTag", st.tag));
		pi_lua_settable(l, "angularThrust",     st.angThrust);
		pi_lua_settable(l, "capacity",          st.capacity);
		pi_lua_settable(l, "hullMass",          st.hullMass);
		pi_lua_settable(l, "fuelTankMass",      st.fuelTankMass);
		pi_lua_settable(l, "basePrice",         st.baseprice);
		pi_lua_settable(l, "minCrew",           st.minCrew);
		pi_lua_settable(l, "maxCrew",           st.maxCrew);
		pi_lua_settable(l, "hyperdriveClass",   st.hyperdriveClass);
		pi_lua_settable(l, "effectiveExhaustVelocity", st.effectiveExhaustVelocity);
		pi_lua_settable(l, "thrusterFuelUse",   st.GetFuelUseRate());

		lua_newtable(l);
		for (int t = Thruster::THRUSTER_REVERSE; t < Thruster::THRUSTER_MAX; t++)
			pi_lua_settable(l, EnumStrings::GetString("ShipTypeThruster", t), st.linThrust[t]);
		pi_lua_readonly_table_proxy(l, -1);
		lua_setfield(l, -3, "linearThrust");
		lua_pop(l, 1);

		lua_newtable(l);
		for (auto it = st.slots.cbegin(); it != st.slots.cend(); ++it) {
			pi_lua_settable(l, it->first.c_str(), it->second);
		}
		pi_lua_readonly_table_proxy(l, -1);
		luaL_getmetafield(l, -1, "__index");
		if (!lua_getmetatable(l, -1)) {
			lua_newtable(l);
		}
		pi_lua_import(l, "EquipSet");
		luaL_getsubtable(l, -1, "default");
		lua_setfield(l, -3, "__index");
		lua_pop(l, 1);
		lua_setmetatable(l, -2);
		lua_pop(l, 1);
		lua_setfield(l, -3, "equipSlotCapacity");
		lua_pop(l, 1);

		lua_newtable(l);
		for (auto it = st.roles.cbegin(); it != st.roles.cend(); ++it) {
			pi_lua_settable(l, it->first.c_str(), it->second);
		}
		pi_lua_readonly_table_proxy(l, -1);
		lua_setfield(l, -3, "roles");
		lua_pop(l, 1);

		pi_lua_readonly_table_proxy(l, -1);
		lua_setfield(l, -3, iter.first.c_str());
		lua_pop(l, 1);
	}

	lua_getfield(l, LUA_REGISTRYINDEX, "CoreImports");
	pi_lua_readonly_table_proxy(l, -2);
	lua_setfield(l, -2, "ShipDef");
	lua_pop(l, 2);

	LUA_DEBUG_END(l, 0);
}
Esempio n. 29
0
LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  luaL_getmetatable(L, tname);
  lua_setmetatable(L, -2);
}
Esempio n. 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
}