Exemplo n.º 1
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;
}
Exemplo n.º 2
0
// Lua table full of data -> states[] (set the values all at once! :D :D)
static int lib_setState(lua_State *L)
{
	state_t *state;
	lua_remove(L, 1); // don't care about states[] userdata.
	state = &states[luaL_checkinteger(L, 1)]; // get the state to assign to.
	luaL_checktype(L, 2, LUA_TTABLE); // check that we've been passed a table.
	lua_remove(L, 1); // pop state num, don't need it any more.
	lua_settop(L, 1); // cut the stack here. the only thing left now is the table of data we're assigning to the state.

	if (hud_running)
		return luaL_error(L, "Do not alter states in HUD rendering code!");

	// clear the state to start with, in case of missing table elements
	memset(state,0,sizeof(state_t));
	state->tics = -1;

	lua_pushnil(L);
	while (lua_next(L, 1)) {
		lua_Integer i = 0;
		const char *str = NULL;
		lua_Integer value;
		if (lua_isnumber(L, 2))
			i = lua_tointeger(L, 2);
		else
			str = luaL_checkstring(L, 2);

		if (i == 1 || (str && fastcmp(str, "sprite"))) {
			value = luaL_checkinteger(L, 3);
			if (value < SPR_NULL || value >= NUMSPRITES)
				return luaL_error(L, "sprite number %d is invalid.", value);
			state->sprite = (spritenum_t)value;
		} else if (i == 2 || (str && fastcmp(str, "frame"))) {
			state->frame = (UINT32)luaL_checkinteger(L, 3);
		} else if (i == 3 || (str && fastcmp(str, "tics"))) {
			state->tics = (INT32)luaL_checkinteger(L, 3);
		} else if (i == 4 || (str && fastcmp(str, "action"))) {
			switch(lua_type(L, 3))
			{
			case LUA_TNIL: // Null? Set the action to nothing, then.
				state->action.acp1 = NULL;
				break;
			case LUA_TSTRING: // It's a string, expect the name of a built-in action
				LUA_SetActionByName(state, lua_tostring(L, 3));
				break;
			case LUA_TFUNCTION: // It's a function (a Lua function or a C function? either way!)
				lua_getfield(L, LUA_REGISTRYINDEX, LREG_STATEACTION);
				I_Assert(lua_istable(L, -1));
				lua_pushlightuserdata(L, state); // We'll store this function by the state's pointer in the registry.
				lua_pushvalue(L, 3); // Bring it to the top of the stack
				lua_rawset(L, -3); // Set it in the registry
				lua_pop(L, 1); // pop LREG_STATEACTION
				state->action.acp1 = (actionf_p1)A_Lua; // Set the action for the userdata.
				break;
			default: // ?!
				return luaL_typerror(L, 3, "function");
			}
		} else if (i == 5 || (str && fastcmp(str, "var1"))) {
			state->var1 = (INT32)luaL_checkinteger(L, 3);
		} else if (i == 6 || (str && fastcmp(str, "var2"))) {
			state->var2 = (INT32)luaL_checkinteger(L, 3);
		} else if (i == 7 || (str && fastcmp(str, "nextstate"))) {
			value = luaL_checkinteger(L, 3);
			if (value < S_NULL || value >= NUMSTATES)
				return luaL_error(L, "nextstate number %d is invalid.", value);
			state->nextstate = (statenum_t)value;
		}
		lua_pop(L, 1);
	}
	return 0;
}
Exemplo n.º 3
0
/**
 * walk through the content array
 *
 * content = { "<pre>", { file = "/content" } , "</pre>" }
 *
 * header["Content-Type"] = "text/html"
 *
 * return 200
 */
static int
magnet_attach_content(server * srv, connection * con, plugin_data * p,
					  lua_State * L)
{
	UNUSED(p);
	/**
	 * get the environment of the function
	 */

	assert(lua_isfunction(L, -1));
	lua_getfenv(L, -1);			/* -1 is the function */

	lua_getfield(L, -1, "lighty");	/* lighty.* from the env */
	assert(lua_istable(L, -1));

	lua_getfield(L, -1, "content");	/* lighty.content */
	if (lua_istable(L, -1))
	{
		int i;
		/*
		 * header is found, and is a table 
		 */

		for (i = 1;; i++)
		{
			lua_rawgeti(L, -1, i);

			/*
			 * -1 is the value and should be the value ... aka a table 
			 */
			if (lua_isstring(L, -1))
			{
				size_t s_len = 0;
				const char *s = lua_tolstring(L, -1, &s_len);

				chunkqueue_append_mem(con->write_queue, s, s_len + 1);
			} else if (lua_istable(L, -1))
			{
				lua_getfield(L, -1, "filename");
				lua_getfield(L, -2, "length");
				lua_getfield(L, -3, "offset");

				if (lua_isstring(L, -3))
				{				/* filename has to be a string */
					buffer *fn = buffer_init();
					stat_cache_entry *sce;

					buffer_copy_string(fn, lua_tostring(L, -3));

					if (HANDLER_GO_ON ==
						stat_cache_get_entry(srv, con, fn, &sce))
					{
						off_t off = 0;
						off_t len = 0;

						if (lua_isnumber(L, -1))
						{
							off = lua_tonumber(L, -1);
						}

						if (lua_isnumber(L, -2))
						{
							len = lua_tonumber(L, -2);
						} else
						{
							len = sce->st.st_size;
						}

						if (off < 0)
						{
							return luaL_error(L,
											  "offset for '%s' is negative",
											  fn->ptr);
						}

						if (len < off)
						{
							return luaL_error(L,
											  "offset > length for '%s'",
											  fn->ptr);
						}

						chunkqueue_append_file(con->write_queue,
											   fn, off, len - off);
					}

					buffer_free(fn);
				} else
				{
					lua_pop(L, 3 + 2);	/* correct the stack */

					return luaL_error(L,
									  "content[%d] is a table and requires the field \"filename\"",
									  i);
				}

				lua_pop(L, 3);
			} else if (lua_isnil(L, -1))
			{
				/*
				 * oops, end of list 
				 */

				lua_pop(L, 1);

				break;
			} else
			{
				lua_pop(L, 4);

				return luaL_error(L,
								  "content[%d] is neither a string nor a table: ",
								  i);
			}

			lua_pop(L, 1);		/* pop the content[...] table */
		}
	} else
	{
		return luaL_error(L, "lighty.content has to be a table");
	}
	lua_pop(L, 1);				/* pop the header-table */
	lua_pop(L, 1);				/* pop the lighty-table */
	lua_pop(L, 1);				/* php the function env */

	return 0;
}
Exemplo n.º 4
0
Arquivo: g_lua.c Projeto: otty/cake3
/*
=================
G_RunLuaFunction
=================
*/
void G_RunLuaFunction(const char *func, const char *sig, ...)
{
	va_list         vl;
	int             narg, nres;	// number of arguments and results
	lua_State      *L = g_luaState;
	
	if(!func || !func[0])
		return;

	va_start(vl, sig);
	lua_getglobal(L, func);		// get function

	// push arguments
	narg = 0;
	while(*sig)
	{
		switch (*sig++)
		{
			case 'd':
				// double argument
				lua_pushnumber(L, va_arg(vl, double));
				break;

			case 'i':
				// int argument
				lua_pushnumber(L, va_arg(vl, int));
				break;

			case 's':
				// string argument
				lua_pushstring(L, va_arg(vl, char *));
				break;
				
			case 'e':
				// entity argument
				lua_pushentity(L, va_arg(vl, gentity_t *));
				break;
				
			case 'v':
				// vector argument
				lua_pushvector(L, va_arg(vl, vec_t *));
				break;

			case '>':
				goto endwhile;

			default:
				G_Printf("G_RunLuaFunction: invalid option (%c)\n", *(sig - 1));
		}
		narg++;
		luaL_checkstack(L, 1, "too many arguments");
	}
  endwhile:

	// do the call
	nres = strlen(sig);			// number of expected results
	if(lua_pcall(L, narg, nres, 0) != 0)	// do the call
		G_Printf("G_RunLuaFunction: error running function `%s': %s\n", func, lua_tostring(L, -1));

	// retrieve results
	nres = -nres;				// stack index of first result
	while(*sig)
	{							// get results
		switch (*sig++)
		{

			case 'd':
				// double result
				if(!lua_isnumber(L, nres))
					G_Printf("G_RunLuaFunction: wrong result type\n");
				*va_arg(vl, double *) = lua_tonumber(L, nres);

				break;

			case 'i':			
				// int result
				if(!lua_isnumber(L, nres))
					G_Printf("G_RunLuaFunction: wrong result type\n");
				*va_arg(vl, int *) = (int)lua_tonumber(L, nres);

				break;

			case 's':
				// string result
				if(!lua_isstring(L, nres))
					G_Printf("G_RunLuaFunction: wrong result type\n");
				*va_arg(vl, const char **) = lua_tostring(L, nres);

				break;

			default:
				G_Printf("G_RunLuaFunction: invalid option (%c)\n", *(sig - 1));
		}
		nres++;
	}
	va_end(vl);
}
Exemplo n.º 5
0
void CLuaRules::Cob2Lua(const LuaHashString& name, const CUnit* unit,
                        int& argsCount, int args[MAX_LUA_COB_ARGS])
{
	static int callDepth = 0;
	if (callDepth >= 16) {
		logOutput.Print("CLuaRules::Cob2Lua() call overflow: %s\n",
		                name.GetString().c_str());
		args[0] = 0; // failure
		return;
	}

	LUA_CALL_IN_CHECK(L);

	const int top = lua_gettop(L);

	if (!lua_checkstack(L, top + 1 + 3 + argsCount)) {
		logOutput.Print("CLuaRules::Cob2Lua() lua_checkstack() error: %s\n",
		                name.GetString().c_str());
		args[0] = 0; // failure
		lua_settop(L, top);
		return;
	}

	if (!name.GetGlobalFunc(L)) {
		logOutput.Print("CLuaRules::Cob2Lua() missing function: %s\n",
		                name.GetString().c_str());
		args[0] = 0; // failure
		lua_settop(L, top);
		return;
	}

	lua_pushnumber(L, unit->id);
	lua_pushnumber(L, unit->unitDef->id);
	lua_pushnumber(L, unit->team);
	for (int a = 0; a < argsCount; a++) {
		lua_pushnumber(L, args[a]);
	}

	// call the routine
	callDepth++;
	const int* oldArgs = currentCobArgs;
	currentCobArgs = args;

	const bool error = !RunCallIn(name, 3 + argsCount, LUA_MULTRET);

	currentCobArgs = oldArgs;
	callDepth--;

	// bail on error
	if (error) {
		args[0] = 0; // failure
		lua_settop(L, top);
		return;
	}

	// get the results
	const int retArgs = std::min(lua_gettop(L) - top, (MAX_LUA_COB_ARGS - 1));
	for (int a = 1; a <= retArgs; a++) {
		const int index = (a + top);
		if (lua_isnumber(L, index)) {
			args[a] = lua_toint(L, index);
		}
		else if (lua_isboolean(L, index)) {
			args[a] = lua_toboolean(L, index) ? 1 : 0;
		}
		else if (lua_istable(L, index)) {
			lua_rawgeti(L, index, 1);
			lua_rawgeti(L, index, 2);
			if (lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
				const int x = lua_toint(L, -2);
				const int z = lua_toint(L, -1);
				args[a] = PACKXZ(x, z);
			} else {
				args[a] = 0;
			}
			lua_pop(L, 2);
		}
		else {
			args[a] = 0;
		}
	}

	args[0] = 1; // success
	lua_settop(L, top);
	return;
}
Exemplo n.º 6
0
int luas_call(luas_state* s, const char* mod, const char* func, const char* sig, ...) {
    lua_State* L = s->l;
    if (_get_function(L, mod, func) != 0) {
        LOG_ERROR("lua call function [%s.%s] error : no function", mod, func);
        return -1;
    }
    
    int top = lua_gettop(L);
    int res;
    int residx;
    int r;

    va_list ap;
    va_start(ap, sig);
    int args = 0;
    
    while(*sig) {
        switch(*sig++) {
        case 'b':
            lua_pushboolean(L, va_arg(ap, int));
            break;
        case 'd':
            lua_pushnumber(L, va_arg(ap, int));
            break;
        case 'u':
            lua_pushnumber(L, va_arg(ap, unsigned int));
            break;
        case 'f':
            lua_pushnumber(L, va_arg(ap, double));
            break;
        case 's':
            lua_pushstring(L, va_arg(ap, const char*));
            break;
        case 'P':
            lua_pushlightuserdata(L, va_arg(ap, void*));
            break;
        case 'p':
            luas_push_obj(L, va_arg(ap, void*), va_arg(ap, const char*));
            break;
        case ':':
            goto call;
        default:
            goto err_exit;
        }
        ++args;
    }

call:
    res = strlen(sig);
    residx = -res;
    r = lua_pcall(L, args, res, s->traceback);
    if (r != LUA_OK) {
        LOG_ERROR("lua call function [%s.%s] error : %s", mod, func, lua_tostring(L, -1));
        goto err_exit;
    }

    while (*sig) {
        switch (*sig++) {
        case 'b':
            if (!lua_isboolean(L, residx))
                goto err_res;
            *va_arg(ap, int*) = (int)lua_toboolean(L, residx);
            break;
        case 'd':
            if (!lua_isnumber(L, residx))
                goto err_res;
            *va_arg(ap, int*) = (int)lua_tointeger(L, residx);
            break;
        case 'u':
            if (!lua_isnumber(L, residx))
                goto err_res;
            *va_arg(ap, unsigned int*) = (unsigned int)lua_tounsigned(L, residx);
            break;
        case 'f':
            if (!lua_isnumber(L, residx))
                goto err_res;
            *va_arg(ap, double*) = (double)lua_tonumber(L, residx);
            break;
        case 's':
            if (!lua_isstring(L, residx))
                goto err_res;
            *va_arg(ap, const char**) = lua_tostring(L, residx);
            break;
        default:
            goto err_exit;
        }
        ++residx;
    }
    return 0;

err_res:
    LOG_ERROR("lua call function [%s.%s] error : return need '%c'#%d", 
            mod, func, *(sig-1), res + residx + 1);
err_exit:
    lua_settop(L, top);
    return -1;
}
Exemplo n.º 7
0
template<> unsigned long long Eluna::CHECKVAL<unsigned long long>(lua_State* luastate, int narg)
{
    if (lua_isnumber(luastate, narg))
        return static_cast<unsigned long long>(CHECKVAL<uint32>(luastate, narg));
    return *(Eluna::CHECKOBJ<unsigned long long>(luastate, narg, true));
}
Exemplo n.º 8
0
Arquivo: ldblib.c Projeto: viticm/pap2
static int db_getinfo (lua_State *L) {
  lua_Debug ar;
  int arg;
  //add by cuiwei 07.8.30
  int i;
  char aparms[1024] = {0};
  //add end
  lua_State *L1 = getthread(L, &arg);
  const char *options = luaL_optstring(L, arg+2, "flnSu");
  if (lua_isnumber(L, arg+1)) {
    if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) {
      lua_pushnil(L);  /* level out of range */
      return 1;
    }
  }
  else if (lua_isfunction(L, arg+1)) {
    lua_pushfstring(L, ">%s", options);
    options = lua_tostring(L, -1);
    lua_pushvalue(L, arg+1);
    lua_xmove(L, L1, 1);
  }
  else
    return luaL_argerror(L, arg+1, "function or level expected");
  if (!lua_getinfo(L1, options, &ar))
    return luaL_argerror(L, arg+2, "invalid option");
  lua_createtable(L, 0, 2);
  if (strchr(options, 'S')) {
    settabss(L, "source", ar.source);
    settabss(L, "short_src", ar.short_src);
    settabsi(L, "linedefined", ar.linedefined);
    settabsi(L, "lastlinedefined", ar.lastlinedefined);
    settabss(L, "what", ar.what);
  }
  if (strchr(options, 'l'))
    settabsi(L, "currentline", ar.currentline);
  if (strchr(options, 'u'))
  {
    settabsi(L, "nups", ar.nups);
	//add by cuiwei 07.8.30
	if (ar.what != "C" )
	{
		settabsi(L, "npars", ar.npars);
		settabsi(L, "has3dot", ar.has3dot?1:0);
		for ( i = 1; i <= ar.npars; i++ )
		{
			strcat(aparms, ar.parms[i-1]);
			if ( i != ar.npars || ar.has3dot)
			{
				strcat(aparms, ",");
			}
		}
		if ( ar.has3dot )
		{
			strcat(aparms, "...");
		}	settabss(L, "strparms", aparms);
	}
	//add end
  }
  if (strchr(options, 'n')) {
    settabss(L, "name", ar.name);
    settabss(L, "namewhat", ar.namewhat);
  }
  if (strchr(options, 'L'))
    treatstackoption(L, L1, "activelines");
  if (strchr(options, 'f'))
    treatstackoption(L, L1, "func");
  return 1;  /* return table */
}
Exemplo n.º 9
0
/**
 * @brief Mods player using the power of Lua.
 */
static void faction_modPlayerLua( int f, double mod, const char *source, int secondary )
{
   Faction *faction;
   lua_State *L;
   int errf;
   double old, delta;
   HookParam hparam[3];

   faction = &faction_stack[f];

   /* Make sure it's not static. */
   if (faction_isFlag(faction, FACTION_STATIC))
      return;

   L     = faction->state;
   old   = faction->player;

   if (L == NULL)
      faction->player += mod;
   else {
#if DEBUGGING
      lua_pushcfunction(L, nlua_errTrace);
      errf = -6;
#else /* DEBUGGING */
      errf = 0;
#endif /* DEBUGGING */

      /* Set up the function:
       * faction_hit( current, amount, source, secondary ) */
      lua_getglobal(   L, "faction_hit" );
      lua_pushnumber(  L, faction->player );
      lua_pushnumber(  L, mod );
      lua_pushstring(  L, source );
      lua_pushboolean( L, secondary );

      /* Call function. */
      if (lua_pcall( L, 4, 1, errf )) { /* An error occurred. */
         WARN("Faction '%s': %s", faction->name, lua_tostring(L,-1));
#if DEBUGGING
         lua_pop( L, 2 );
#else /* DEBUGGING */
         lua_pop( L, 1 );
#endif /* DEBUGGING */
         return;
      }

      /* Parse return. */
      if (!lua_isnumber( L, -1 ))
         WARN( "Lua script for faction '%s' did not return a number from 'faction_hit(...)'.", faction->name );
      else
         faction->player = lua_tonumber( L, -1 );
#if DEBUGGING
      lua_pop( L, 2 );
#else /* DEBUGGING */
      lua_pop( L, 1 );
#endif /* DEBUGGING */
   }

   /* Sanitize just in case. */
   faction_sanitizePlayer( faction );

   /* Run hook if necessary. */
   delta = faction->player - old;
   if (fabs(delta) > 1e-10) {
      hparam[0].type    = HOOK_PARAM_FACTION;
      hparam[0].u.lf    = f;
      hparam[1].type    = HOOK_PARAM_NUMBER;
      hparam[1].u.num   = delta;
      hparam[2].type    = HOOK_PARAM_SENTINEL;
      hooks_runParam( "standing", hparam );

      /* Tell space the faction changed. */
      space_factionChange();
   }
}
Exemplo n.º 10
0
/**
 * puts a table with content of a xavp
 */
static int lua_sr_xavp_get(lua_State *L)
{
	str xavp_name;
	int indx = 0;
	sr_lua_env_t *env_L;
	sr_xavp_t *avp;
	int num_param = 0;
	int param = -1;
	int all_flag = 0;
	int simple_flag = 0;
	lua_Number elem = 1;
	int xavp_size = 0;

	env_L = sr_lua_env_get();
	num_param = lua_gettop(L);
	if(num_param<2 && num_param>3)
	{
		LM_ERR("wrong number of parameters [%d]\n", num_param);
		return 0;
	}

	if(num_param==3)
	{
		if(!lua_isnumber(L, param))
		{
			LM_ERR("invalid int parameter\n");
			return 0;
		}
		simple_flag = lua_tointeger(L, param);
		param = param - 1;
	}

	if(!lua_isnumber(L, param))
	{
		if(lua_isnil(L, param))
		{
			all_flag = 1;
		}
		else
		{
			LM_ERR("invalid parameter, must be int or nil\n");
			return 0;
		}
	}
	else
	{
		indx = lua_tointeger(L, param);
	}
	param = param - 1;
	xavp_name.s = (char*)lua_tostring(L, param);
	if(xavp_name.s==NULL || env_L->msg==NULL)
	{
		LM_ERR("No xavp name in %d param\n", param);
		return 0;
	}
	xavp_name.len = strlen(xavp_name.s);
	if(all_flag>0) {
		indx = 0;
		lua_newtable(L);
	}
	xavp_size = xavp_count(&xavp_name, NULL);
	if(indx<0)
	{
		if((indx*-1)>xavp_size)
		{
			LM_ERR("can't get xavp:%.*s index:%d\n", xavp_name.len, xavp_name.s, indx);
			lua_pushnil(L);
			return 1;
		}
		indx = xavp_size + indx;
	}

	avp = xavp_get_by_index(&xavp_name, indx, NULL);
	do
	{
		if(avp==NULL){
			LM_ERR("can't get xavp:%.*s index:%d\n", xavp_name.len, xavp_name.s, indx);
			lua_pushnil(L);
			return 1;
		}
		if(all_flag!=0) {
			lua_pushnumber(L, elem);
			elem = elem + 1;
		}
		lua_sr_push_xavp_table(L, avp, simple_flag);
		if(all_flag!=0) {
			lua_rawset(L, -3);
			indx = indx + 1;
			avp = xavp_get_by_index(&xavp_name, indx, NULL);
		}
		else return 1;
	}while(avp!=NULL);

	return 1;
}
Exemplo n.º 11
0
	int create_class::stage1(lua_State* L)
	{

	#ifndef LUABIND_NO_ERROR_CHECKING

		if (lua_gettop(L) != 1 || lua_type(L, 1) != LUA_TSTRING || lua_isnumber(L, 1))
		{
			lua_pushstring(L, "invalid construct, expected class name");
			lua_error(L);
		}

		if (std::strlen(lua_tostring(L, 1)) != lua_strlen(L, 1))
		{
			lua_pushstring(L, "luabind does not support class names with extra nulls");
			lua_error(L);
		}

	#endif

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

		int stack_level = lua_gettop(L);
		//////////////////////////////////////////////////////////////////////////
		// Here we are trying to add the class to the namespace in the local variable "this" if exist
		//////////////////////////////////////////////////////////////////////////

		int index = LUA_GLOBALSINDEX;
		lua_Debug ar;
		if ( lua_getstack (L, 1, &ar) )
		{
			int i = 1;
			const char *name;
			while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
				if (!strcmp("this",name)) {
					if (lua_istable(L,-1))
						index = lua_gettop(L);
					else
						lua_pop(L, 1);
					break;
				}
				lua_pop(L, 1);  /* remove variable value */
			}
		}
		
		//////////////////////////////////////////////////////////////////////////
		// End of change
		//////////////////////////////////////////////////////////////////////////

		void* c = lua_newuserdata(L, sizeof(class_rep));
		new(c) class_rep(L, name);

		// make the class globally available
		lua_pushstring(L, name);
		lua_pushvalue(L, -2);
		lua_settable(L, index);
		if (index != LUA_GLOBALSINDEX)
			lua_remove(L,index);

		// also add it to the closure as return value
		lua_pushcclosure(L, &stage2, 1);

		int stack_level2 = lua_gettop(L);
		return 1;
	}
Exemplo n.º 12
0
int pklua_lua_socket_recv(lua_State *L)
{
  pk_log(PK_LOG_LUA_DEBUG, "pklua_lua_socket_recv(%p)", L);

  pklua_buffer read_buffer;
  int sockfd = _pklua_lua_socket_get_sockfd(L);
  unsigned int wantbytes = 0;
  unsigned int maxbytes = 8*1024;
  char sock_input[4096];

  if (lua_gettop(L) > 1 && lua_isnumber(L, 2))
    wantbytes = lua_tointeger(L, 2);
  if (lua_gettop(L) > 2 && lua_isnumber(L, 3))
    maxbytes = lua_tointeger(L, 3);
  if (maxbytes < wantbytes)
    maxbytes = wantbytes;

  _pklua_lua_socket_get_buffer(L, "_read_buffer", &read_buffer);
  int buffer_pos = lua_gettop(L);
  size_t i = 0;
  while (1) {
    /* Check if we have a line in our buffer, return if so! */
    for (; i < read_buffer.length; i++) {
      if (((wantbytes < 1) && (read_buffer.bytes[i] == '\n')) ||
          ((wantbytes > 0) && (i >= wantbytes)) ||
          (i >= maxbytes)) {
        /* Copy the line/chunk... */
        size_t eol = i;
        if (wantbytes < 1)
          while (eol && (read_buffer.bytes[eol] == '\r' ||
                         read_buffer.bytes[eol] == '\n')) eol--;
        lua_pushlstring(L, read_buffer.bytes, eol+1);
        /* Adjust the read_buffer and pop from the stack */
        _pklua_lua_socket_shift_buffer(L, "_read_buffer", i+1, &read_buffer);
        _pklua_lua_socket_free_buffer(L, buffer_pos);
        /* Return line! */
        return 1;
      }
    }
    /* Only have partial line, read more data from socket */
    int read_bytes = wantbytes ? (wantbytes - read_buffer.length) : 4096;
    if (read_bytes > 4096) read_bytes = 4096;
    while ((read_bytes = PKS_read(sockfd, sock_input, read_bytes)) < 0) {
       /* Is this really an error? */
       if ((errno != 0) && (errno != EINTR) && (errno != EAGAIN)) break;
    }
    /* If EOF, return buffer contents */
    if (read_bytes <= 0) {
      lua_pushlstring(L, read_buffer.bytes, read_buffer.length);
      /* Adjust the read_buffer and pop from the stack */
      _pklua_lua_socket_shift_buffer(L, "_read_buffer", i+1, &read_buffer);
      _pklua_lua_socket_free_buffer(L, buffer_pos);
      /* Return line! */
      return 1;
    }
    /* Else, append to buffer, keep looping */
    else {
      _pklua_lua_socket_free_buffer(L, buffer_pos);
      _pklua_lua_socket_append_buffer(L, "_read_buffer",
                                      sock_input, read_bytes);
      _pklua_lua_socket_get_buffer(L, "_read_buffer", &read_buffer);
      buffer_pos = lua_gettop(L);
    }
  }
  _pklua_lua_socket_free_buffer(L, buffer_pos);
  return 0;
}
Exemplo n.º 13
0
void read_object_properties(lua_State *L, int index,
		ObjectProperties *prop)
{
	if(index < 0)
		index = lua_gettop(L) + 1 + index;
	if(!lua_istable(L, index))
		return;

	prop->hp_max = getintfield_default(L, -1, "hp_max", 10);

	getboolfield(L, -1, "physical", prop->physical);
	getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);

	getfloatfield(L, -1, "weight", prop->weight);

	lua_getfield(L, -1, "collisionbox");
	if(lua_istable(L, -1))
		prop->collisionbox = read_aabb3f(L, -1, 1.0);
	lua_pop(L, 1);

	getstringfield(L, -1, "visual", prop->visual);

	getstringfield(L, -1, "mesh", prop->mesh);

	lua_getfield(L, -1, "visual_size");
	if(lua_istable(L, -1))
		prop->visual_size = read_v2f(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "textures");
	if(lua_istable(L, -1)){
		prop->textures.clear();
		int table = lua_gettop(L);
		lua_pushnil(L);
		while(lua_next(L, table) != 0){
			// key at index -2 and value at index -1
			if(lua_isstring(L, -1))
				prop->textures.push_back(lua_tostring(L, -1));
			else
				prop->textures.push_back("");
			// removes value, keeps key for next iteration
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "colors");
	if (lua_istable(L, -1)) {
		int table = lua_gettop(L);
		prop->colors.clear();
		for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) {
			video::SColor color(255, 255, 255, 255);
			read_color(L, -1, &color);
			prop->colors.push_back(color);
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "spritediv");
	if(lua_istable(L, -1))
		prop->spritediv = read_v2s16(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, -1, "initial_sprite_basepos");
	if(lua_istable(L, -1))
		prop->initial_sprite_basepos = read_v2s16(L, -1);
	lua_pop(L, 1);

	getboolfield(L, -1, "is_visible", prop->is_visible);
	getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
	getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
	if (getfloatfield(L, -1, "stepheight", prop->stepheight))
		prop->stepheight *= BS;
	lua_getfield(L, -1, "automatic_face_movement_dir");
	if (lua_isnumber(L, -1)) {
		prop->automatic_face_movement_dir = true;
		prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
	} else if (lua_isboolean(L, -1)) {
		prop->automatic_face_movement_dir = lua_toboolean(L, -1);
		prop->automatic_face_movement_dir_offset = 0.0;
	}
	lua_pop(L, 1);
	getboolfield(L, -1, "backface_culling", prop->backface_culling);

	getstringfield(L, -1, "nametag", prop->nametag);
	lua_getfield(L, -1, "nametag_color");
	if (!lua_isnil(L, -1)) {
		video::SColor color = prop->nametag_color;
		if (read_color(L, -1, &color))
			prop->nametag_color = color;
	}
	lua_pop(L, 1);

	lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec");
	if (lua_isnumber(L, -1)) {
		prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1);
	}
	lua_pop(L, 1);
	getstringfield(L, -1, "infotext", prop->infotext);
}
Exemplo n.º 14
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;
}
Exemplo n.º 15
0
inline void _SaveTableValue(lua::NativeState hLua,lua::Table *table,T key)
{
	// ... [value]

	int   type = lua_type(hLua, -1);

	if ( type==LUA_TSTRING )
	{
		lua::Str   _value;
		CheckVarFromLua(hLua,&_value,-1);
		lua::Var   value(_value);
		(*table)[key] = value;
	}
	else if ( type==LUA_TTABLE )
	{
		lua::Table   subTable;
		_VisitTable(hLua,&subTable);

		lua::Var   value = subTable;
		(*table)[key] = value;
	}
	// Just in case.
	else if ( type==LUA_TNIL )
	{
		// This element is not exist.
	}
	else if ( type==LUA_TNONE )
	{
		lua::Log<<"error:No one know what type is it"<<lua::End;
	}
	else if ( type==LUA_TLIGHTUSERDATA )
	{
		lua::Ptr   value;
		CheckVarFromLua(hLua,&value,-1);
		(*table)[key] = value;
	}
	else if ( type==LUA_TBOOLEAN )
	{
		lua::Bool   value;
		CheckVarFromLua(hLua,&value,-1);
		(*table)[key] = value;
	}
	#ifndef _LUAPP_KEEP_LOCAL_LUA_VARIABLE_
	else if ( type==LUA_TFUNCTION )
	{
		lua::Func   value;
		(*table)[key] = value;
	}
	else if ( type==LUA_TTHREAD )
	{
		lua::Task   value;
		(*table)[key] = value;
	}
	else if ( type==LUA_TUSERDATA )
	{
		lua::User   value;
		(*table)[key] = value;
	}
	#endif
	else if ( lua_isinteger(hLua, -1) )
	{
		lua::Int   value;
		CheckVarFromLua(hLua,&value,-1);
		(*table)[key] = value;
	}
	else if ( lua_isnumber(hLua, -1) )
	{
		lua::Num   value;
		CheckVarFromLua(hLua,&value,-1);
		(*table)[key] = value;
	}
	else
	{
		// drop else value.
	}

	// ... [value]
}
Exemplo n.º 16
0
static void interror (lua_State *L, int arg) {
  if (lua_isnumber(L, arg))
    luaL_argerror(L, arg, "number has no integer representation");
  else
    tag_error(L, arg, LUA_TNUMBER);
}
Exemplo n.º 17
0
void sinsp_chisel::parse_view_column(lua_State *ls, OUT chisel_desc* cd, OUT void* columns)
{
	vector<sinsp_view_column_info>* cols = (vector<sinsp_view_column_info>*)columns;

	lua_pushnil(ls);

	string tmpstr;
	string name;
	string description;
	string field;
	string filterfield;
	uint32_t colsize = 0xffffffff;
	uint32_t flags = TEF_NONE;
	sinsp_field_aggregation aggregation = A_NONE;
	sinsp_field_aggregation groupby_aggregation = A_NONE;
	vector<string> tags;

	while(lua_next(ls, -2) != 0)
	{
		string fldname = lua_tostring(ls, -2);

		if(fldname == "name")
		{
			name = lua_tostring(ls, -1);
		}
		else if(fldname == "description")
		{
			description = lua_tostring(ls, -1);
		}
		else if(fldname == "field")
		{
			field = lua_tostring(ls, -1);
		}
		else if(fldname == "filterfield")
		{
			filterfield = lua_tostring(ls, -1);
		}
		else if(fldname == "colsize")
		{
			if(lua_isnumber(ls, -1))
			{
				colsize = (uint32_t)lua_tonumber(ls, -1);
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a number");
			}
		}
		else if(fldname == "is_key")
		{
			if(lua_isboolean(ls, -1))
			{
				bool ik = (lua_toboolean(ls, -1) != 0);
				if(ik)
				{
					flags |= TEF_IS_KEY;
				}
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
			}
		}
		else if(fldname == "filter_in_child_only")
		{
			if(lua_isboolean(ls, -1))
			{
				bool ik = (lua_toboolean(ls, -1) != 0);
				if(ik)
				{
					flags |= TEF_FILTER_IN_CHILD_ONLY;
				}
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
			}
		}
		else if(fldname == "is_groupby_key")
		{
			if(lua_isboolean(ls, -1))
			{
				bool ik = (lua_toboolean(ls, -1) != 0);
				if(ik)
				{
					flags |= TEF_IS_GROUPBY_KEY;
				}
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
			}
		}
		else if(fldname == "is_sorting")
		{
			if(lua_isboolean(ls, -1))
			{
				bool ik = (lua_toboolean(ls, -1) != 0);
				if(ik)
				{
					flags |= TEF_IS_SORT_COLUMN;
				}
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
			}
		}
		else if(fldname == "aggregation")
		{
			if(lua_isstring(ls, -1))
			{
				string ag = lua_tostring(ls, -1);

				aggregation = string_to_aggregation(ag);
			}
		}
		else if(fldname == "groupby_aggregation")
		{
			if(lua_isstring(ls, -1))
			{
				string ag = lua_tostring(ls, -1);

				groupby_aggregation = string_to_aggregation(ag);
			}
		}
		else if(fldname == "tags")
		{
			if(lua_istable(ls, -1))
			{
				lua_pushnil(ls);

				while(lua_next(ls, -2) != 0)
				{
					if(lua_isstring(ls, -1))
					{
						tmpstr = lua_tostring(ls, -1);
						tags.push_back(tmpstr);
					}
					else
					{
						throw sinsp_exception("tags column entries must be strings");
					}

					lua_pop(ls, 1);
				}
			}
			else
			{
				throw sinsp_exception(string(lua_tostring(ls, -2)) + " is not a table");
			}
		}

		lua_pop(ls, 1);
	}

	if(filterfield != "" && ((flags & TEF_IS_KEY) == 0) && ((flags & TEF_IS_GROUPBY_KEY) == 0))
	{
		throw sinsp_exception("wrong view column syntax: filterfield specified for a non key column");
	}

	cols->push_back(sinsp_view_column_info(field,
		name,
		description,
		colsize,
		(uint32_t)flags,
		aggregation,
		groupby_aggregation,
		tags,
		filterfield));
}
Exemplo n.º 18
0
float luaL_check_number(int32 numArg) {
	lua_Object o = lua_getparam(numArg);
	luaL_arg_check(lua_isnumber(o), numArg, "number expected");
	return lua_getnumber(o);
}
Exemplo n.º 19
0
template<> long long Eluna::CHECKVAL<long long>(lua_State* luastate, int narg)
{
    if (lua_isnumber(luastate, narg))
        return static_cast<long long>(CHECKVAL<double>(luastate, narg));
    return *(Eluna::CHECKOBJ<long long>(luastate, narg, true));
}
Exemplo n.º 20
0
Arquivo: mqtt.c Projeto: pvvx/EspLua
// Lua: mqtt:lwt( topic, message, qos, retain, function(client) )
static int mqtt_socket_lwt( lua_State* L )
{
  NODE_DBG("enter mqtt_socket_lwt.\n");
  uint8_t stack = 1;
  size_t topicSize, msgSize;
  NODE_DBG("mqtt_socket_lwt.\n");
  lmqtt_userdata *mud = NULL;
  const char *lwtTopic, *lwtMsg;
  uint8_t lwtQoS, lwtRetain;

  mud = (lmqtt_userdata *)luaL_checkudata( L, stack, "mqtt.socket" );
  luaL_argcheck( L, mud, stack, "mqtt.socket expected" );

  if(mud == NULL)
    return 0;

  stack++;
  lwtTopic = luaL_checklstring( L, stack, &topicSize );
  if (lwtTopic == NULL)
  {
    return luaL_error( L, "need lwt topic");
  }

  stack++;
  lwtMsg = luaL_checklstring( L, stack, &msgSize );
  if (lwtMsg == NULL)
  {
    return luaL_error( L, "need lwt message");
  }

  if(mud->connect_info.will_topic){    // free the previous one if there is any
    c_free(mud->connect_info.will_topic);
    mud->connect_info.will_topic = NULL;
  }
  if(mud->connect_info.will_message){
    c_free(mud->connect_info.will_message);
    mud->connect_info.will_message = NULL;
  }

  mud->connect_info.will_topic = (uint8_t*) c_zalloc( topicSize + 1 );
  mud->connect_info.will_message = (uint8_t*) c_zalloc( msgSize + 1 );
  if(!mud->connect_info.will_topic || !mud->connect_info.will_message){
    if(mud->connect_info.will_topic){
      c_free(mud->connect_info.will_topic);
      mud->connect_info.will_topic = NULL;
    }
    if(mud->connect_info.will_message){
      c_free(mud->connect_info.will_message);
      mud->connect_info.will_message = NULL;
    }
    return luaL_error( L, "not enough memory");
  }
  c_memcpy(mud->connect_info.will_topic, lwtTopic, topicSize);
  mud->connect_info.will_topic[topicSize] = 0;
  c_memcpy(mud->connect_info.will_message, lwtMsg, msgSize);
  mud->connect_info.will_message[msgSize] = 0;

  if ( lua_isnumber(L, stack) )
  {
    mud->connect_info.will_qos = lua_tointeger(L, stack);
    stack++;
  }
  if ( lua_isnumber(L, stack) )
  {
    mud->connect_info.will_retain = lua_tointeger(L, stack);
    stack++;
  }

  NODE_DBG("mqtt_socket_lwt: topic: %s, message: %s, qos: %d, retain: %d\n",
      mud->connect_info.will_topic,
      mud->connect_info.will_message,
      mud->connect_info.will_qos,
      mud->connect_info.will_retain);
  NODE_DBG("leave mqtt_socket_lwt.\n");
  return 0;
}
Exemplo n.º 21
0
LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  lua_Integer d = lua_tointeger(L, narg);
  if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
    tag_error(L, narg, LUA_TNUMBER);
  return d;
}
Exemplo n.º 22
0
Arquivo: mqtt.c Projeto: pvvx/EspLua
// Lua: mqtt.Client(clientid, keepalive, user, pass)
static int mqtt_socket_client( lua_State* L )
{
  NODE_DBG("enter mqtt_socket_client.\n");

  lmqtt_userdata *mud;
  char tempid[20] = {0};
  c_sprintf(tempid, "%s%x", "NodeMCU_", system_get_chip_id() );
  NODE_DBG_(tempid);
  NODE_DBG("\n");
  
  const char *clientId = tempid, *username = NULL, *password = NULL;
  size_t idl = c_strlen(tempid);
  size_t unl = 0, pwl = 0;
  int keepalive = 0;
  int stack = 1;
  unsigned secure = 0;
  int top = lua_gettop(L);

  // create a object
  mud = (lmqtt_userdata *)lua_newuserdata(L, sizeof(lmqtt_userdata));
  // pre-initialize it, in case of errors
  mud->L = NULL;
  mud->self_ref = LUA_NOREF;
  mud->cb_connect_ref = LUA_NOREF;
  mud->cb_disconnect_ref = LUA_NOREF;

  mud->cb_message_ref = LUA_NOREF;
  mud->cb_suback_ref = LUA_NOREF;
  mud->cb_puback_ref = LUA_NOREF;
  mud->pesp_conn = NULL;
  mud->secure = 0;

  mud->keep_alive_tick = 0;
  mud->event_timeout = 0;
  mud->connState = MQTT_INIT;
  mud->connected = false;
  c_memset(&mud->mqttTimer, 0, sizeof(ETSTimer));
  c_memset(&mud->mqtt_state, 0, sizeof(mqtt_state_t));
  c_memset(&mud->connect_info, 0, sizeof(mqtt_connect_info_t));

  // set its metatable
  luaL_getmetatable(L, "mqtt.socket");
  lua_setmetatable(L, -2);

  mud->L = L;   // L for mqtt module.

  if( lua_isstring(L,stack) )   // deal with the clientid string
  {
    clientId = luaL_checklstring( L, stack, &idl );
    stack++;
  }

  if(lua_isnumber( L, stack ))
  {   
    keepalive = luaL_checkinteger( L, stack);
    stack++;
  }

  if(keepalive == 0){
    keepalive = MQTT_DEFAULT_KEEPALIVE;
  }

  if(lua_isstring( L, stack )){
    username = luaL_checklstring( L, stack, &unl );
    stack++;
  }
  if(username == NULL)
    unl = 0;
  NODE_DBG("lengh username: %d\r\n", unl);

  if(lua_isstring( L, stack )){
    password = luaL_checklstring( L, stack, &pwl );
    stack++;
  }
  if(password == NULL)
    pwl = 0;
  NODE_DBG("lengh password: %d\r\n", pwl);

  // TODO: check the zalloc result.
  mud->connect_info.client_id = (uint8_t *)c_zalloc(idl+1);
  mud->connect_info.username = (uint8_t *)c_zalloc(unl + 1);
  mud->connect_info.password = (uint8_t *)c_zalloc(pwl + 1);
  if(!mud->connect_info.client_id || !mud->connect_info.username || !mud->connect_info.password){
    if(mud->connect_info.client_id) {
      c_free(mud->connect_info.client_id);
      mud->connect_info.client_id = NULL;
    }
    if(mud->connect_info.username) {
      c_free(mud->connect_info.username);
      mud->connect_info.username = NULL;
    }
    if(mud->connect_info.password) {
      c_free(mud->connect_info.password);
      mud->connect_info.password = NULL;
    }
  	return luaL_error(L, "not enough memory");
  }

  c_memcpy(mud->connect_info.client_id, clientId, idl);
  mud->connect_info.client_id[idl] = 0;
  c_memcpy(mud->connect_info.username, username, unl);
  mud->connect_info.username[unl] = 0;
  c_memcpy(mud->connect_info.password, password, pwl);
  mud->connect_info.password[pwl] = 0;
  
  NODE_DBG("MQTT: Init info: %s, %s, %s\r\n", mud->connect_info.client_id, mud->connect_info.username, mud->connect_info.password);

  mud->connect_info.clean_session = 1;
  mud->connect_info.will_qos = 0;
  mud->connect_info.will_retain = 0;
  mud->connect_info.keepalive = keepalive;

  mud->mqtt_state.pending_msg_q = NULL;
  mud->mqtt_state.auto_reconnect = 0;
  mud->mqtt_state.port = 1883;
  mud->mqtt_state.connect_info = &mud->connect_info;

  NODE_DBG("leave mqtt_socket_client.\n");
  return 1;
}
Exemplo n.º 23
0
int CLuaVector4Defs::Create ( lua_State* luaVM )
{
    CVector4D vector;

    CScriptArgReader argStream ( luaVM );
    if ( argStream.NextIsTable () )
    {
        lua_pushvalue ( luaVM, 1 );

        lua_pushstring ( luaVM, "x" );
        lua_rawget ( luaVM, -2 );
        if ( lua_isnumber ( luaVM, -1 ) )
        {
            vector.fX = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }
        else
        {
            lua_pop ( luaVM, 1 );
            lua_rawgeti ( luaVM, -1, 1 );
            if ( lua_isnumber ( luaVM, -1 ) )
                vector.fX = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }

        lua_pushstring ( luaVM, "y" );
        lua_rawget ( luaVM, -2 );
        if ( lua_isnumber ( luaVM, -1 ) )
        {
            vector.fY = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }
        else
        {
            lua_pop ( luaVM, 1 );
            lua_rawgeti ( luaVM, -1, 2 );
            if ( lua_isnumber ( luaVM, -1 ) )
                vector.fY = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }

        lua_pushstring ( luaVM, "z" );
        lua_rawget ( luaVM, -2 );
        if ( lua_isnumber ( luaVM, -1 ) )
        {
            vector.fZ = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }
        else
        {
            lua_pop ( luaVM, 1 );
            lua_rawgeti ( luaVM, -1, 3 );
            if ( lua_isnumber ( luaVM, -1 ) )
                vector.fZ = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }

        lua_pushstring ( luaVM, "w" );
        lua_rawget ( luaVM, -2 );
        if ( lua_isnumber ( luaVM, -1 ) )
        {
            vector.fW = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }
        else
        {
            lua_pop ( luaVM, 1 );
            lua_rawgeti ( luaVM, -1, 4 );
            if ( lua_isnumber ( luaVM, -1 ) )
                vector.fW = ( float ) lua_tonumber ( luaVM, -1 );
            lua_pop ( luaVM, 1 );
        }
    }
    else if ( argStream.NextIsNumber () )
    {
        argStream.ReadNumber ( vector.fX );
        if ( argStream.NextIsNumber () )
        {
            argStream.ReadNumber ( vector.fY );
            if ( argStream.NextIsNumber () )
                argStream.ReadNumber ( vector.fZ );
            if ( argStream.NextIsNumber () )
                argStream.ReadNumber ( vector.fW );
        }
    }
    else if ( argStream.NextIsVector4D () )
    {
        argStream.ReadVector4D ( vector );
    }
    lua_pushvector ( luaVM, vector );
    return 1;
}
Exemplo n.º 24
0
Arquivo: mqtt.c Projeto: pvvx/EspLua
// Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
static int mqtt_socket_connect( lua_State* L )
{
  NODE_DBG("enter mqtt_socket_connect.\n");
  lmqtt_userdata *mud = NULL;
  unsigned port = 1883;
  size_t il;
  ip_addr_t ipaddr;
  const char *domain;
  int stack = 1;
  unsigned secure = 0, auto_reconnect = 0;
  int top = lua_gettop(L);

  mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
  luaL_argcheck(L, mud, stack, "mqtt.socket expected");
  stack++;
  if(mud == NULL)
    return 0;

  if(mud->connected){
    return luaL_error(L, "already connected");
  }

  if(mud->pesp_conn){   //TODO: should I free tcp struct directly or ask user to call close()???
    mud->pesp_conn->reverse = NULL;
    if(mud->pesp_conn->proto.tcp)
      c_free(mud->pesp_conn->proto.tcp);
    mud->pesp_conn->proto.tcp = NULL;
    c_free(mud->pesp_conn);
    mud->pesp_conn = NULL;
  }

  struct espconn *pesp_conn = NULL;
	pesp_conn = mud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
	if(!pesp_conn)
		return luaL_error(L, "not enough memory");

	pesp_conn->proto.udp = NULL;
	pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp));
	if(!pesp_conn->proto.tcp){
		c_free(pesp_conn);
		pesp_conn = mud->pesp_conn = NULL;
		return luaL_error(L, "not enough memory");
	}
	// reverse is for the callback function
	pesp_conn->reverse = mud;
	pesp_conn->type = ESPCONN_TCP;
	pesp_conn->state = ESPCONN_NONE;
  mud->connected = false;

  if( (stack<=top) && lua_isstring(L,stack) )   // deal with the domain string
  {
    domain = luaL_checklstring( L, stack, &il );

    stack++;
    if (domain == NULL)
    {
      domain = "127.0.0.1";
    }
    ipaddr.addr = ipaddr_addr(domain);
    c_memcpy(pesp_conn->proto.tcp->remote_ip, &ipaddr.addr, 4);
    NODE_DBG("TCP ip is set: ");
    NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
    NODE_DBG("\n");
  }

  if ( (stack<=top) && lua_isnumber(L, stack) )
  {
    port = lua_tointeger(L, stack);
    stack++;
    NODE_DBG("TCP port is set: %d.\n", port);
  }
  pesp_conn->proto.tcp->remote_port = port;
  pesp_conn->proto.tcp->local_port = espconn_port();
  mud->mqtt_state.port = port;

  if ( (stack<=top) && lua_isnumber(L, stack) )
  {
    secure = lua_tointeger(L, stack);
    stack++;
    if ( secure != 0 && secure != 1 ){
      secure = 0; // default to 0
    }
  } else {
    secure = 0; // default to 0
  }
  mud->secure = secure; // save

  if ( (stack<=top) && lua_isnumber(L, stack) )
  {
    auto_reconnect = lua_tointeger(L, stack);
    stack++;
    if ( auto_reconnect != 0 && auto_reconnect != 1 ){
      auto_reconnect = 0; // default to 0
    }
  } else {
    auto_reconnect = 0; // default to 0
  }
  mud->mqtt_state.auto_reconnect = auto_reconnect;

  // call back function when a connection is obtained, tcp only
  if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
    lua_pushvalue(L, stack);  // copy argument (func) to the top of stack
    if(mud->cb_connect_ref != LUA_NOREF)
      luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
    mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
    stack++;
  }

  lua_pushvalue(L, 1);  // copy userdata to the top of stack
  if(mud->self_ref != LUA_NOREF)
    luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
  mud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);

  espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
  espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);

  os_timer_disarm(&mud->mqttTimer);
  os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
  // timer started in socket_connect()

  if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0))
  {
    host_ip.addr = 0;
    dns_reconn_count = 0;
    if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_found)){
      socket_dns_found(domain, &host_ip, pesp_conn);  // ip is returned in host_ip.
    }
  }
  else
  {
    socket_connect(pesp_conn);
  }

  NODE_DBG("leave mqtt_socket_connect.\n");
  return 0;
}
Exemplo n.º 25
0
//////////////////////////////////////////////////////////////////////
// Constructor:
static int ar_write(lua_State *L) {
    struct archive** self_ref;

    static struct {
        const char *name;
        int (*setter)(struct archive *);
    } names[] = {
        /* Copied from archive_write_set_format_by_name.c */
        { "ar",         archive_write_set_format_ar_bsd },
        { "arbsd",      archive_write_set_format_ar_bsd },
        { "argnu",      archive_write_set_format_ar_svr4 },
        { "arsvr4",     archive_write_set_format_ar_svr4 },
        { "cpio",       archive_write_set_format_cpio },
        { "mtree",      archive_write_set_format_mtree },
        { "newc",       archive_write_set_format_cpio_newc },
        { "odc",        archive_write_set_format_cpio },
        { "pax",        archive_write_set_format_pax },
        { "posix",      archive_write_set_format_pax },
        { "shar",       archive_write_set_format_shar },
        { "shardump",   archive_write_set_format_shar_dump },
        { "ustar",      archive_write_set_format_ustar },
        /* New ones to more closely match the C API */
        { "ar_bsd",     archive_write_set_format_ar_bsd },
        { "ar_svr4",    archive_write_set_format_ar_svr4 },
        { "cpio_newc",  archive_write_set_format_cpio_newc },
        { "pax_restricted", archive_write_set_format_pax_restricted },
        { "shar_dump",  archive_write_set_format_shar_dump },
        { NULL,         NULL }
    };
    int idx = 0;
    const char* name;

    luaL_checktype(L, 1, LUA_TTABLE);
    self_ref = (struct archive**)
        lua_newuserdata(L, sizeof(struct archive*)); // {ud}
    luaL_getmetatable(L, AR_WRITE); // {ud}, [write]
    lua_setmetatable(L, -2); // {ud}
    __ref_count++;
    *self_ref = archive_write_new();

    // Register it in the weak metatable:
    ar_registry_set(L, *self_ref);

    // Create an environment to store a reference to the writer:
    lua_createtable(L, 1, 0); // {ud}, {}
    lua_pushliteral(L, "writer"); // {ud}, {}, "writer"
    lua_rawget(L, 1); // {ud}, {}, fn
    if ( ! lua_isfunction(L, -1) ) {
        err("MissingArgument: required parameter 'writer' must be a function");
    }
    lua_setfield(L, -2, "writer");
    lua_setfenv(L, -2); // {ud}

    // Extract various fields and prepare the archive:
    lua_getfield(L, 1, "bytes_per_block");
    if ( ! lua_isnil(L, -1) &&
         ARCHIVE_OK != archive_write_set_bytes_per_block(*self_ref, lua_tointeger(L, -1)) )
    {
        err("archive_write_set_bytes_per_block: %s", archive_error_string(*self_ref));
    }
    lua_pop(L, 1);

    lua_getfield(L, 1, "bytes_in_last_block");
    if ( ! lua_isnil(L, -1) &&
         ARCHIVE_OK != archive_write_set_bytes_in_last_block(*self_ref, lua_tointeger(L, -1)) )
    {
        err("archive_write_set_bytes_in_last_block: %s", archive_error_string(*self_ref));
    }
    lua_pop(L, 1);

    lua_getfield(L, 1, "skip_file");
    if ( ! lua_isnil(L, -1) ) {
        dev_t dev;
        ino_t ino;

        if ( LUA_TTABLE != lua_type(L, -1) ) {
            err("skip_file member must be a table object");
        }

        lua_getfield(L, -1, "dev");
        if ( ! lua_isnumber(L, -1) ) {
            err("skip_file.dev member must be a number");
        }
        dev = (dev_t)lua_tonumber(L, -1);
        lua_pop(L, 1);

        lua_getfield(L, -1, "ino");
        if ( ! lua_isnumber(L, -1) ) {
            err("skip_file.ino member must be a number");
        }
        ino = (ino_t)lua_tonumber(L, -1);
        lua_pop(L, 1);

        if ( ARCHIVE_OK != archive_write_set_skip_file(*self_ref, dev, ino) ) {
            err("archive_write_set_skip_file: %s", archive_error_string(*self_ref));
        }
    }
    lua_pop(L, 1);

    lua_getfield(L, 1, "format");
    if ( lua_isnil(L, -1) ) {
        lua_pop(L, 1);
        lua_pushliteral(L, "posix");
    }
    name = lua_tostring(L, -1);
    for ( ;; idx++ ) {
        if ( names[idx].name == NULL ) {
            err("archive_write_set_format_*: No such format '%s'", name);
        }
        if ( strcmp(name, names[idx].name) == 0 ) break;
    }
    if ( ARCHIVE_OK != (names[idx].setter)(*self_ref) ) {
        err("archive_write_set_format_%s: %s", name, archive_error_string(*self_ref));
    }
    lua_pop(L, 1);

    lua_getfield(L, 1, "compression");
    if ( ! lua_isnil(L, -1) ) {
        static struct {
            const char *name;
            int (*setter)(struct archive *);
        } names[] = {
            { "bzip2",    archive_write_add_filter_bzip2 },
            { "compress", archive_write_add_filter_compress },
            { "gzip",     archive_write_add_filter_gzip },
            { "lzma",     archive_write_add_filter_lzma },
            { "xz",       archive_write_add_filter_xz },
            { NULL,       NULL }
        };
        int idx = 0;
        const char* name = lua_tostring(L, -1);
        for ( ;; idx++ ) {
            if ( names[idx].name == NULL ) {
                err("archive_write_set_compression_*: No such compression '%s'", name);
            }
            if ( strcmp(name, names[idx].name) == 0 ) break;
        }
        if ( ARCHIVE_OK != (names[idx].setter)(*self_ref) ) {
            err("archive_write_set_compression_%s: %s", name, archive_error_string(*self_ref));
        }
    }
    lua_pop(L, 1);

    lua_getfield(L, 1, "options");
    if ( ! lua_isnil(L, -1) &&
         ARCHIVE_OK != archive_write_set_options(*self_ref, lua_tostring(L, -1)) )
    {
        err("archive_write_set_options: %s",  archive_error_string(*self_ref));
    }
    lua_pop(L, 1);


    if ( ARCHIVE_OK != archive_write_open(*self_ref, L, NULL, &ar_write_cb, NULL) ) {
        err("archive_write_open: %s", archive_error_string(*self_ref));
    }

    return 1;
}
Exemplo n.º 26
0
// hud_change(self, id, stat, data)
int ObjectRef::l_hud_change(lua_State *L)
{
	ObjectRef *ref = checkobject(L, 1);
	Player *player = getplayer(ref);
	if (player == NULL)
		return 0;

	u32 id = lua_isnumber(L, 2) ? lua_tonumber(L, 2) : -1;

	HudElement *e = player->getHud(id);
	if (!e)
		return 0;

	HudElementStat stat = HUD_STAT_NUMBER;
	if (lua_isstring(L, 3)) {
		int statint;
		std::string statstr = lua_tostring(L, 3);
		stat = string_to_enum(es_HudElementStat, statint, statstr) ?
				(HudElementStat)statint : HUD_STAT_NUMBER;
	}

	void *value = NULL;
	switch (stat) {
		case HUD_STAT_POS:
			e->pos = read_v2f(L, 4);
			value = &e->pos;
			break;
		case HUD_STAT_NAME:
			e->name = luaL_checkstring(L, 4);
			value = &e->name;
			break;
		case HUD_STAT_SCALE:
			e->scale = read_v2f(L, 4);
			value = &e->scale;
			break;
		case HUD_STAT_TEXT:
			e->text = luaL_checkstring(L, 4);
			value = &e->text;
			break;
		case HUD_STAT_NUMBER:
			e->number = luaL_checknumber(L, 4);
			value = &e->number;
			break;
		case HUD_STAT_ITEM:
			e->item = luaL_checknumber(L, 4);
			value = &e->item;
			break;
		case HUD_STAT_DIR:
			e->dir = luaL_checknumber(L, 4);
			value = &e->dir;
			break;
		case HUD_STAT_ALIGN:
			e->align = read_v2f(L, 4);
			value = &e->align;
			break;
		case HUD_STAT_OFFSET:
			e->offset = read_v2f(L, 4);
			value = &e->offset;
			break;
		case HUD_STAT_WORLD_POS:
			e->world_pos = read_v3f(L, 4);
			value = &e->world_pos;
			break;
		case HUD_STAT_SIZE:
			e->size = read_v2s32(L, 4);
			value = &e->size;
			break;
	}

	getServer(L)->hudChange(player, id, stat, value);

	lua_pushboolean(L, true);
	return 1;
}
Exemplo n.º 27
0
// Lua table full of data -> mobjinfo[]
static int lib_setMobjInfo(lua_State *L)
{
	mobjinfo_t *info;
	lua_remove(L, 1); // don't care about mobjinfo[] userdata.
	info = &mobjinfo[luaL_checkinteger(L, 1)]; // get the mobjinfo to assign to.
	luaL_checktype(L, 2, LUA_TTABLE); // check that we've been passed a table.
	lua_remove(L, 1); // pop mobjtype num, don't need it any more.
	lua_settop(L, 1); // cut the stack here. the only thing left now is the table of data we're assigning to the mobjinfo.

	if (hud_running)
		return luaL_error(L, "Do not alter mobjinfo in HUD rendering code!");

	// clear the mobjinfo to start with, in case of missing table elements
	memset(info,0,sizeof(mobjinfo_t));
	info->doomednum = -1; // default to no editor value
	info->spawnhealth = 1; // avoid 'dead' noclip behaviors

	lua_pushnil(L);
	while (lua_next(L, 1)) {
		lua_Integer i = 0;
		const char *str = NULL;
		lua_Integer value;
		if (lua_isnumber(L, 2))
			i = lua_tointeger(L, 2);
		else
			str = luaL_checkstring(L, 2);

		if (i == 1 || (str && fastcmp(str,"doomednum")))
			info->doomednum = (INT32)luaL_checkinteger(L, 3);
		else if (i == 2 || (str && fastcmp(str,"spawnstate"))) {
			value = luaL_checkinteger(L, 3);
			if (value < S_NULL || value >= NUMSTATES)
				return luaL_error(L, "spawnstate number %d is invalid.", value);
			info->spawnstate = (statenum_t)value;
		} else if (i == 3 || (str && fastcmp(str,"spawnhealth")))
			info->spawnhealth = (INT32)luaL_checkinteger(L, 3);
		else if (i == 4 || (str && fastcmp(str,"seestate"))) {
			value = luaL_checkinteger(L, 3);
			if (value < S_NULL || value >= NUMSTATES)
				return luaL_error(L, "seestate number %d is invalid.", value);
			info->seestate = (statenum_t)value;
		} else if (i == 5 || (str && fastcmp(str,"seesound"))) {
			value = luaL_checkinteger(L, 3);
			if (value < sfx_None || value >= NUMSFX)
				return luaL_error(L, "seesound number %d is invalid.", value);
			info->seesound = (sfxenum_t)value;
		} else if (i == 6 || (str && fastcmp(str,"reactiontime")))
			info->reactiontime = (INT32)luaL_checkinteger(L, 3);
		else if (i == 7 || (str && fastcmp(str,"attacksound")))
			info->attacksound = luaL_checkinteger(L, 3);
		else if (i == 8 || (str && fastcmp(str,"painstate")))
			info->painstate = luaL_checkinteger(L, 3);
		else if (i == 9 || (str && fastcmp(str,"painchance")))
			info->painchance = (INT32)luaL_checkinteger(L, 3);
		else if (i == 10 || (str && fastcmp(str,"painsound")))
			info->painsound = luaL_checkinteger(L, 3);
		else if (i == 11 || (str && fastcmp(str,"meleestate")))
			info->meleestate = luaL_checkinteger(L, 3);
		else if (i == 12 || (str && fastcmp(str,"missilestate")))
			info->missilestate = luaL_checkinteger(L, 3);
		else if (i == 13 || (str && fastcmp(str,"deathstate")))
			info->deathstate = luaL_checkinteger(L, 3);
		else if (i == 14 || (str && fastcmp(str,"xdeathstate")))
			info->xdeathstate = luaL_checkinteger(L, 3);
		else if (i == 15 || (str && fastcmp(str,"deathsound")))
			info->deathsound = luaL_checkinteger(L, 3);
		else if (i == 16 || (str && fastcmp(str,"speed")))
			info->speed = (fixed_t)luaL_checkinteger(L, 3);
		else if (i == 17 || (str && fastcmp(str,"radius")))
			info->radius = (fixed_t)luaL_checkinteger(L, 3);
		else if (i == 18 || (str && fastcmp(str,"height")))
			info->height = (fixed_t)luaL_checkinteger(L, 3);
		else if (i == 19 || (str && fastcmp(str,"dispoffset")))
			info->dispoffset = (INT32)luaL_checkinteger(L, 3);
		else if (i == 20 || (str && fastcmp(str,"mass")))
			info->mass = (INT32)luaL_checkinteger(L, 3);
		else if (i == 21 || (str && fastcmp(str,"damage")))
			info->damage = (INT32)luaL_checkinteger(L, 3);
		else if (i == 22 || (str && fastcmp(str,"activesound")))
			info->activesound = luaL_checkinteger(L, 3);
		else if (i == 23 || (str && fastcmp(str,"flags")))
			info->flags = (INT32)luaL_checkinteger(L, 3);
		else if (i == 24 || (str && fastcmp(str,"raisestate"))) {
			info->raisestate = luaL_checkinteger(L, 3);
		}
		lua_pop(L, 1);
	}
	return 0;
}
Exemplo n.º 28
0
//------------------------------------------------------------------------------
inline void CheckVarFromLua(lua::NativeState hLua,lua::Var *t,int i)
{
	int   type = lua_type(hLua, i);

	if ( type==LUA_TSTRING )
	{
		lua::Str   var;
		CheckVarFromLua(hLua,&var,i);
		*t = var;
	}
	else if ( type==LUA_TBOOLEAN )
	{
		lua::Bool   var;
		CheckVarFromLua(hLua,&var,i);
		*t = var;
	}
	else if ( type==LUA_TNIL )
	{
		*t = lua::Var();
	}
	else if ( type==LUA_TNONE )
	{
		lua::Log<<"error:No one know what type is it. That's new"<<lua::End;
	}
	else if ( type==LUA_TLIGHTUSERDATA )
	{
		lua::Ptr   var;
		CheckVarFromLua(hLua,&var,i);
		*t = var;
	}
	else if ( type==LUA_TTABLE )
	{
		lua::Table   table;
		CheckVarFromLua(hLua,&table,i);
		*t = table;
	}
	#ifndef _LUAPP_KEEP_LOCAL_LUA_VARIABLE_
	else if ( type==LUA_TFUNCTION )
	{
		lua::Func   var;
		*t = var;
	}
	else if ( type==LUA_TTHREAD )
	{
		lua::Task   var;
		*t = var;
	}
	else if ( type==LUA_TUSERDATA )
	{
		lua::User   var;
		*t = var;
	}
	#endif
	else if ( lua_isinteger(hLua, i) )
	{
		lua::Int   var;
		CheckVarFromLua(hLua,&var,i);
		*t = var;
	}
	else if ( lua_isnumber(hLua, i) )
	{
		lua::Num   var;
		CheckVarFromLua(hLua,&var,i);
		*t = var;
	}
	else
	{
		lua::Log<<"error:you get something luapp can't handle with"<<lua::End;
		*t = lua::Var();
	}
}
Exemplo n.º 29
0
static handler_t
magnet_attract(server * srv, connection * con, plugin_data * p, buffer * name)
{
	lua_State *L;
	int lua_return_value = -1;
	/*
	 * get the script-context 
	 */


	L = script_cache_get_script(srv, con, p->cache, name);

	if (lua_isstring(L, -1))
	{
		log_error_write(srv, __FILE__, __LINE__,
						"sbss",
						"loading script", name, "failed:", lua_tostring(L, -1));

		lua_pop(L, 1);

		assert(lua_gettop(L) == 0);	/* only the function should be on the stack 
									 */

		con->http_status = 500;
		con->mode = DIRECT;

		return HANDLER_FINISHED;
	}

	lua_pushstring(L, "lighty.srv");
	lua_pushlightuserdata(L, srv);
	lua_settable(L, LUA_REGISTRYINDEX);	/* registery[<id>] = srv */

	lua_pushstring(L, "lighty.con");
	lua_pushlightuserdata(L, con);
	lua_settable(L, LUA_REGISTRYINDEX);	/* registery[<id>] = con */

	lua_atpanic(L, magnet_atpanic);

	/**
	 * we want to create empty environment for our script
	 *
	 * setmetatable({}, {__index = _G})
	 *
	 * if a function, symbol is not defined in our env, __index will lookup
	 * in the global env.
	 *
	 * all variables created in the script-env will be thrown
	 * away at the end of the script run.
	 */
	lua_newtable(L);			/* my empty environment aka {} (sp += 1) */

	/*
	 * we have to overwrite the print function 
	 */
	lua_pushcfunction(L, magnet_print);	/* (sp += 1) */
	lua_setfield(L, -2, "print");	/* -1 is the env we want to set(sp -= 1) */

	/**
	 * lighty.request[] has the HTTP-request headers
	 * lighty.content[] is a table of string/file
	 * lighty.header[] is a array to set response headers
	 */

	lua_newtable(L);			/* lighty.* (sp += 1) */

	lua_newtable(L);			/* {} (sp += 1) */
	lua_newtable(L);			/* the meta-table for the request-table (sp +=
								 * 1) */
	lua_pushcfunction(L, magnet_reqhdr_get);	/* (sp += 1) */
	lua_setfield(L, -2, "__index");	/* (sp -= 1) */
	lua_setmetatable(L, -2);	/* tie the metatable to request (sp -= 1) */
	lua_setfield(L, -2, "request");	/* content = {} (sp -= 1) */

	lua_newtable(L);			/* {} (sp += 1) */
	lua_newtable(L);			/* the meta-table for the request-table (sp +=
								 * 1) */
	lua_pushcfunction(L, magnet_env_get);	/* (sp += 1) */
	lua_setfield(L, -2, "__index");	/* (sp -= 1) */
	lua_pushcfunction(L, magnet_env_set);	/* (sp += 1) */
	lua_setfield(L, -2, "__newindex");	/* (sp -= 1) */
	lua_setmetatable(L, -2);	/* tie the metatable to request (sp -= 1) */
	lua_setfield(L, -2, "env");	/* content = {} (sp -= 1) */

	lua_newtable(L);			/* {} (sp += 1) */
	lua_newtable(L);			/* the meta-table for the request-table (sp +=
								 * 1) */
	lua_pushcfunction(L, magnet_status_get);	/* (sp += 1) */
	lua_setfield(L, -2, "__index");	/* (sp -= 1) */
	lua_pushcfunction(L, magnet_status_set);	/* (sp += 1) */
	lua_setfield(L, -2, "__newindex");	/* (sp -= 1) */
	lua_setmetatable(L, -2);	/* tie the metatable to request (sp -= 1) */
	lua_setfield(L, -2, "status");	/* content = {} (sp -= 1) */

	/*
	 * add empty 'content' and 'header' tables 
	 */
	lua_newtable(L);			/* {} (sp += 1) */
	lua_setfield(L, -2, "content");	/* content = {} (sp -= 1) */

	lua_newtable(L);			/* {} (sp += 1) */
	lua_setfield(L, -2, "header");	/* header = {} (sp -= 1) */

	lua_pushinteger(L, MAGNET_RESTART_REQUEST);
	lua_setfield(L, -2, "RESTART_REQUEST");

	lua_pushcfunction(L, magnet_stat);	/* (sp += 1) */
	lua_setfield(L, -2, "stat");	/* -1 is the env we want to set (sp -= 1) */

	lua_setfield(L, -2, "lighty");	/* lighty.* (sp -= 1) */

	lua_newtable(L);			/* the meta-table for the new env (sp += 1) */
	lua_pushvalue(L, LUA_GLOBALSINDEX);	/* (sp += 1) */
	lua_setfield(L, -2, "__index");	/* { __index = _G } (sp -= 1) */
	lua_setmetatable(L, -2);	/* setmetatable({}, {__index = _G}) (sp -= 1) */


	lua_setfenv(L, -2);			/* on the stack should be a modified env (sp -= 
								 * 1) */

	if (lua_pcall(L, 0, 1, 0))
	{
		log_error_write(srv, __FILE__, __LINE__,
						"ss", "lua_pcall():", lua_tostring(L, -1));
		lua_pop(L, 1);			/* remove the error-msg and the function copy
								 * from the stack */

		assert(lua_gettop(L) == 1);	/* only the function should be on the stack 
									 */

		con->http_status = 500;
		con->mode = DIRECT;

		return HANDLER_FINISHED;
	}

	/*
	 * we should have the function-copy and the return value on the stack 
	 */
	assert(lua_gettop(L) == 2);

	if (lua_isnumber(L, -1))
	{
		/*
		 * if the ret-value is a number, take it 
		 */
		lua_return_value = (int) lua_tonumber(L, -1);
	}
	lua_pop(L, 1);				/* pop the ret-value */

	magnet_copy_response_header(srv, con, p, L);

	if (lua_return_value > 99)
	{
		con->http_status = lua_return_value;
		con->file_finished = 1;

		/*
		 * try { ... 
		 */
		if (0 == setjmp(exceptionjmp))
		{
			magnet_attach_content(srv, con, p, L);
			if (!chunkqueue_is_empty(con->write_queue))
			{
				con->mode = p->id;
			}
		} else
		{
			/*
			 * } catch () { 
			 */
			con->http_status = 500;
			con->mode = DIRECT;
		}

		assert(lua_gettop(L) == 1);	/* only the function should be on the stack 
									 */

		/*
		 * we are finished 
		 */
		return HANDLER_FINISHED;
	} else if (MAGNET_RESTART_REQUEST == lua_return_value)
	{
		assert(lua_gettop(L) == 1);	/* only the function should be on the stack 
									 */

		return HANDLER_COMEBACK;
	} else
	{
		assert(lua_gettop(L) == 1);	/* only the function should be on the stack 
									 */

		return HANDLER_GO_ON;
	}
}
Exemplo n.º 30
0
/*
 * Arguments: sd_udata, [count (number) | membuf_udata,
 *	from (sock_addr_udata), options (string) ...]
 * Returns: [string | count (number) | false (EAGAIN)]
 */
static int
sock_recv (lua_State *L)
{
    static const int o_flags[] = {
	MSG_OOB, MSG_PEEK,
#ifndef _WIN32
	MSG_WAITALL
#endif
    };
    static const char *const o_names[] = {
	"oob", "peek",
#ifndef _WIN32
	"waitall",
#endif
	NULL
    };
    sd_t sd = (sd_t) lua_unboxinteger(L, 1, SD_TYPENAME);
    size_t n = !lua_isnumber(L, 2) ? ~((size_t) 0)
     : (size_t) lua_tointeger(L, 2);
    struct sock_addr *from = !lua_isuserdata(L, 3) ? NULL
     : checkudata(L, 3, SA_TYPENAME);
    struct sockaddr *sap = NULL;
    socklen_t *slp = NULL;
    const size_t len = n;  /* how much total to read */
    size_t rlen;  /* how much to read */
    int nr;  /* number of bytes actually read */
    struct sys_buffer sb;
    char buf[SYS_BUFSIZE];
    unsigned int i, flags = 0;

    sys_buffer_write_init(L, 2, &sb, buf, sizeof(buf));

    for (i = lua_gettop(L); i > 3; --i) {
	flags |= o_flags[luaL_checkoption(L, i, NULL, o_names)];
    }
    if (from) {
	sap = &from->u.addr;
	slp = &from->addrlen;
    }
    do {
	rlen = (n <= sb.size) ? n : sb.size;
	sys_vm_leave();
#ifndef _WIN32
	do nr = recvfrom(sd, sb.ptr.w, rlen, flags, sap, slp);
	while (nr == -1 && SYS_ERRNO == EINTR);
#else
	nr = recvfrom(sd, sb.ptr.w, rlen, flags, sap, slp);
#endif
	sys_vm_enter();
	if (nr == -1) break;
	n -= nr;  /* still have to read `n' bytes */
    } while ((n != 0L && nr == (int) rlen)  /* until end of count or eof */
     && sys_buffer_write_next(L, &sb, buf, 0));
    if (nr <= 0 && len == n) {
	if (!nr || !SYS_EAGAIN(SYS_ERRNO)) goto err;
	lua_pushboolean(L, 0);
    } else {
	if (!sys_buffer_write_done(L, &sb, buf, nr))
	    lua_pushinteger(L, len - n);
    }
    return 1;
 err:
    return sys_seterror(L, 0);
}