예제 #1
0
SQInteger Sq_GetLayerRects(HSQUIRRELVM v) {
  const SQChar *What;
  sq_getstring(v, 2, &What);
  int Layer = FindLayerByName(What);
  if(Layer < 0) {
    sq_pushnull(v);
    return 1;
  }

  sq_newarray(v, 0);
  for(LevelRect *Rect = LayerInfos[Layer].Rects; Rect; Rect=Rect->Next) {
    sq_newarray(v, 0);
    sq_pushstring(v, LayerInfos[Layer].TilesetLookup[Rect->Type].Name, -1);
    sq_arrayappend(v, -2);
    sq_pushinteger(v, Rect->X);
    sq_arrayappend(v, -2);
    sq_pushinteger(v, Rect->Y);
    sq_arrayappend(v, -2);
    sq_pushinteger(v, Rect->W);
    sq_arrayappend(v, -2);
    sq_pushinteger(v, Rect->H);
    sq_arrayappend(v, -2);
    sq_pushinteger(v, ((Rect->Flips&SDL_FLIP_HORIZONTAL)!=0)|(((Rect->Flips&SDL_FLIP_VERTICAL)!=0)<<1));
    sq_arrayappend(v, -2);
    if(Rect->ExtraInfo)
      sq_pushstring(v, Rect->ExtraInfo, -1);
    else
      sq_pushnull(v);
    sq_arrayappend(v, -2);
    sq_arrayappend(v, -2);
  }

  return 1;
}
예제 #2
0
SQInteger ts::script_api::car_store::getCars(HSQUIRRELVM vm)
{
    Userdata<Car_store> car_store_udata;
    
    Argument_stream argument_stream(vm, "CarStore::getCars");
    argument_stream(Userdata_reader<Car_store>(car_store_udata));

    if (argument_stream)
    {
        sq_newarray(vm, 0);

        for (auto car_handle : *car_store_udata->local_car_store)
        {
            Stack_guard loop_guard(vm);
            make_userdata(vm, car_handle).push();
            sq_arrayappend(vm, -2);
        }

        for (auto car_handle : *car_store_udata->global_car_store)
        {
            Stack_guard loop_guard(vm);
            make_userdata(vm, car_handle).push();
            sq_arrayappend(vm, -2);
        }

        return 1;
    }

    else
    {
        report_argument_errors(vm, argument_stream);
        return 0;
    }
}
예제 #3
0
static SQRESULT sq_mysql_result_row_as_array(HSQUIRRELVM v){
	SQ_FUNC_VARS(v);
	GET_mysql_result_INSTANCE();
	SQ_OPT_INTEGER(v, 2, row, -1);
    if(row < 0){
        sq_pushstring(v, _curr_row_key, -1);
        if(sq_get(v, 1) == SQ_OK){
            sq_getinteger(v, -1, &row);
        }
    }
    int row_count = dlmysql_num_rows(self);
    if(row < 0 || row >= row_count) return sq_throwerror(v, _SC("invalid row (" _PRINT_INT_FMT ")"), row);

    int col_count = dlmysql_num_fields(self);
    sq_newarray(v, col_count);
    dlmysql_data_seek(self, row);
    const MYSQL_ROW res_row = dlmysql_fetch_row(self);
    unsigned long *lengths = dlmysql_fetch_lengths(self);
    for(int i=0; i < col_count; ++i){
        sq_pushinteger(v, i);
        sq_pushstring(v, (const SQChar*)res_row[i], lengths[i]);
        sq_rawset(v, -3);
    }
	return 1;
}
예제 #4
0
SQInteger CSharedVehicleNatives::GetPosition( SQVM * pVM )
{
	// Get the vehicle id
	SQInteger vehicleId;
	sq_getinteger( pVM, -1, &vehicleId );

	// Is the vehicle active?
	if( pCore->GetVehicleManager()->IsActive( vehicleId ) )
	{
		// Get the vehicle position
		CVector3 vecPosition;
		pCore->GetVehicleManager()->Get( vehicleId )->GetPosition( &vecPosition );

		sq_newarray( pVM, 0 );

		sq_pushfloat( pVM, vecPosition.fX );
		sq_arrayappend( pVM, -2 );

		sq_pushfloat( pVM, vecPosition.fY );
		sq_arrayappend( pVM, -2 );

		sq_pushfloat( pVM, vecPosition.fZ );
		sq_arrayappend( pVM, -2 );

		sq_push( pVM, -1 );
		return 1;
	}

	sq_pushbool( pVM, false );
	return 1;
}
예제 #5
0
SquirrelObject SquirrelVM::CreateArray(int size)
{
	SquirrelObject ret(_VM);
	sq_newarray(_VM,size);
	ret.AttachToStackObject(-1);
	sq_pop(_VM,1);
	return ret;
}
예제 #6
0
/*
 * Push b2Vec2 as an array
 */
void pushVec2(HSQUIRRELVM v, b2Vec2 vec2) {
	sq_newarray(v, 0);
	
	sq_pushfloat(v, vec2.x);
	sq_arrayappend(v, -2);
	
	sq_pushfloat(v, vec2.y);
	sq_arrayappend(v, -2);
}	
예제 #7
0
/* static */ bool ScriptInstance::LoadObjects(HSQUIRRELVM vm)
{
	SlObject(NULL, _script_byte);
	switch (_script_sl_byte) {
		case SQSL_INT: {
			int value;
			SlArray(&value, 1, SLE_INT32);
			if (vm != NULL) sq_pushinteger(vm, (SQInteger)value);
			return true;
		}

		case SQSL_STRING: {
			SlObject(NULL, _script_byte);
			static char buf[256];
			SlArray(buf, _script_sl_byte, SLE_CHAR);
			if (vm != NULL) sq_pushstring(vm, OTTD2SQ(buf), -1);
			return true;
		}

		case SQSL_ARRAY: {
			if (vm != NULL) sq_newarray(vm, 0);
			while (LoadObjects(vm)) {
				if (vm != NULL) sq_arrayappend(vm, -2);
				/* The value is popped from the stack by squirrel. */
			}
			return true;
		}

		case SQSL_TABLE: {
			if (vm != NULL) sq_newtable(vm);
			while (LoadObjects(vm)) {
				LoadObjects(vm);
				if (vm != NULL) sq_rawset(vm, -3);
				/* The key (-2) and value (-1) are popped from the stack by squirrel. */
			}
			return true;
		}

		case SQSL_BOOL: {
			SlObject(NULL, _script_byte);
			if (vm != NULL) sq_pushinteger(vm, (SQBool)(_script_sl_byte != 0));
			return true;
		}

		case SQSL_NULL: {
			if (vm != NULL) sq_pushnull(vm);
			return true;
		}

		case SQSL_ARRAY_TABLE_END: {
			return false;
		}

		default: NOT_REACHED();
	}
}
예제 #8
0
void CSquirrelVM::PushArray(const CScriptArguments &array)
{
	sq_newarray(m_pVM, 0);
	for(auto pArgument : array.m_Arguments)
	{
		pArgument->Push(this);

		sq_arrayappend(m_pVM, -2);
	}
}
예제 #9
0
bool CSquirrelArgument::push(SQVM* pVM)
{
	switch(type)
	{
		case OT_NULL:
			sq_pushnull(pVM);
			break;
		case OT_INTEGER:
			sq_pushinteger(pVM, data.i);
			break;
		case OT_BOOL:
			sq_pushbool(pVM, data.b);
			break;
		case OT_FLOAT:
			sq_pushfloat(pVM, data.f);
			break;
		case OT_STRING:
			sq_pushstring(pVM, data.str->Get(), data.str->GetLength());
			break;
		case OT_ARRAY:
			{
				sq_newarray(pVM, 0);

				for(auto pArgument : *data.pArray->GetArguments())
				{
					pArgument->push(pVM);
					sq_arrayappend(pVM, -2);
				}
				break;
			}
		case OT_TABLE:
			{
				sq_newtable(pVM);

				int i = 0;
				assert( data.pArray->GetArguments()->size() % 2 == 0 );
				for(auto iter = data.pArray->GetArguments()->begin(); iter != data.pArray->GetArguments()->end(); ++ iter, ++ i )
				{
					(*iter)->push(pVM);
					++ iter;
					(*iter)->push(pVM);
					sq_createslot(pVM, -3);
				}
				break;
			}
			break;
		default:
			sq_pushnull(pVM); // table, whatsoever. do not even care. fix it if you dare.
			assert(0);
			return false;
	}
	return true;
}
예제 #10
0
SQInteger Sq_GetLayerMap(HSQUIRRELVM v) {
  const SQChar *What;
  sq_getstring(v, 2, &What);
  int Layer = FindLayerByName(What);
  if(Layer < 0) {
    sq_pushnull(v);
    return 1;
  }
  RenderLevelRects(Layer);
  int ArgCount = sq_gettop(v);
  int X = 0, Y = 0, W = LayerInfos[Layer].LayerWidth, H = LayerInfos[Layer].LayerHeight;
  if(ArgCount == 5) {
    sq_getinteger(v, 3, &X);
    sq_getinteger(v, 4, &Y);
    sq_getinteger(v, 5, &W);
    sq_getinteger(v, 6, &H);
    W = abs(W);
    H = abs(H);
    if(X+W > LayerInfos[Layer].LayerWidth)
      W = LayerInfos[Layer].LayerWidth - X;
    if(Y+H > LayerInfos[Layer].LayerHeight)
      H = LayerInfos[Layer].LayerHeight - Y;
  }

  // FIX ME, dumps all the numbers in the first row for some reason
  sq_newarray(v, 0);
  while(H --> 0) {
     Y++;
     sq_newarray(v, 0);
     int OldX = X;
     while(W --> 0) {
       sq_pushinteger(v, TilesetLookupIdToIndex(Layer, LayerInfos[Layer].Map[Y*LayerInfos[Layer].LayerWidth+X++].Graphic));
       sq_arrayappend(v, -2);
     }
     sq_arrayappend(v, -2);
     X = OldX;
  }

  return 1;
}
예제 #11
0
static SQRESULT sq_fossil_delta_analyze(HSQUIRRELVM v) {
    SQ_FUNC_VARS_NO_TOP(v);
    SQ_GET_STRING(v, 2, str_delta);
    int pnCopy, pnInsert;
    int rc = delta_analyze(str_delta, str_delta_size, &pnCopy, &pnInsert);
    if(rc < 0) return sq_throwerror(v, _SC("invalid delta string"));
    sq_newarray(v, 2);
    sq_pushinteger(v, pnCopy);
    sq_arrayset(v, -2, 0);
    sq_pushinteger(v, pnInsert);
    sq_arrayset(v, -2, 1);
    return 1;
}
예제 #12
0
//------------------------------------------------------------------------------
void SN_API pushArray(HSQUIRRELVM vm, const Variant::Array & a)
{
	sq_newarray(vm, a.size());
	for (size_t i = 0; i < a.size(); ++i)
	{
		sq_pushinteger(vm, i);
		pushValue(vm, a[i]);
		if (SQ_FAILED(sq_set(vm, -3)))
		{
			SN_WARNING("Variant => Squirrel: failed to set array index " << i);
		}
	}
}
예제 #13
0
// getTime()
SQInteger CWorldNatives::GetTime(SQVM * pVM)
{
	unsigned char ucHour = 0, ucMinute = 0;
	CTime::GetInstance()->GetTime(&ucHour, &ucMinute);

	sq_newarray(pVM, 0);

	sq_pushinteger(pVM, ucHour);
	sq_arrayappend(pVM, -2);

	sq_pushinteger(pVM, ucMinute);
	sq_arrayappend(pVM, -2);

	return 1;
}
예제 #14
0
/*
 * returns all preference keys
 */
SQInteger emoDatabaseGetPreferenceKeys(HSQUIRRELVM v) {

    std::vector<std::string> keys = engine->database->getPreferenceKeys();

    sq_newarray(v, 0);

    for (unsigned int i = 0; i < keys.size(); i++) {
        sq_pushstring(v, keys[i].c_str(), -1);
        sq_arrayappend(v, -2);
    }

    sq_push(v, -1);

    return 1;
}
예제 #15
0
// getTrafficLightsPhaseDuration()
SQInteger CWorldNatives::GetTrafficLightsPhaseDuration(SQVM * pVM)
{
	sq_newarray(pVM, 0);

	sq_pushbool(pVM, CTrafficLights::GetInstance()->IsUsingDefaultDurations());
	sq_arrayappend(pVM, -2);

	sq_pushinteger(pVM, CTrafficLights::GetInstance()->GetGreenDuration());
	sq_arrayappend(pVM, -2);

	sq_pushinteger(pVM, CTrafficLights::GetInstance()->GetYellowDuration());
	sq_arrayappend(pVM, -2);

	sq_pushinteger(pVM, CTrafficLights::GetInstance()->GetRedDuration());
	sq_arrayappend(pVM, -2);

	return 1;
}
예제 #16
0
static SQInteger _string_split(HSQUIRRELVM v)
{
	const SQChar *str,*seps;
	SQChar *stemp,*tok;
	sq_getstring(v,2,&str);
	sq_getstring(v,3,&seps);
	if(sq_getsize(v,3) == 0) return sq_throwerror(v,_SC("empty separators string"));
	SQInteger memsize = (sq_getsize(v,2)+1)*sizeof(SQChar);
	stemp = sq_getscratchpad(v,memsize);
	memcpy(stemp,str,memsize);
	tok = scstrtok(stemp,seps);
	sq_newarray(v,0);
	while( tok != NULL ) {
		sq_pushstring(v,tok,-1);
		sq_arrayappend(v,-2);
		tok = scstrtok( NULL, seps );
	}
	return 1;
}
예제 #17
0
// getConfig()
SQInteger CServerNatives::GetConfig(SQVM * pVM)
{
	// Create a new table
	sq_newtable(pVM);

	for(std::map<String, SettingsValue *>::iterator iter = CSettings::GetValues()->begin(); iter != CSettings::GetValues()->end(); iter++)
	{
		// Get the setting
		SettingsValue * setting = iter->second;

		// Push the setting name onto the stack
		sq_pushstring(pVM, iter->first.Get(), iter->first.GetLength());

		// Push the value onto the stack
		if(setting->IsBool())
			sq_pushbool(pVM, setting->bValue);
		else if(setting->IsInteger())
			sq_pushinteger(pVM, setting->iValue);
		else if(setting->IsFloat())
			sq_pushfloat(pVM, setting->fValue);
		else if(setting->IsString())
			sq_pushstring(pVM, setting->strValue, setting->strValue.GetLength());
		else if(setting->IsList())
		{
			// Create a new array
			sq_newarray(pVM, 0);

			for(std::list<String>::iterator iter2 = setting->listValue.begin(); iter2 != setting->listValue.end(); iter2++)
			{
				// Push the list value onto the stack
				sq_pushstring(pVM, (*iter2).Get(), (*iter2).GetLength());

				// Create a new array slot
				sq_arrayappend(pVM, -2);
			}
		}

		// Create a new table slot
		sq_createslot(pVM, -3);
	}

	return 1;
}
예제 #18
0
// getVehicles()
SQInteger CSharedVehicleNatives::GetVehicles( SQVM * pVM )
{
	sq_newarray( pVM, 0 );

	// Loop over every vehicle
	for ( int vehicleId = 0; vehicleId < MAX_VEHICLES; vehicleId++ )
	{
		// Is the current vehicle active?
		if ( pCore->GetVehicleManager()->Get( vehicleId ) )
		{
			// Push the vehicle id into the array
			sq_pushinteger( pVM, vehicleId );
			sq_arrayappend( pVM, -2 );
		}
	}

	sq_push( pVM, -1 );
	return 1;
}
예제 #19
0
void Sq_DecodeJSONTable(HSQUIRRELVM v, cJSON *Item) {
  if(!Item)
    return;
  while(Item) {
    if(Item->string)
      sq_pushstring(v, Item->string, -1);
    switch(Item->type) {
      case cJSON_False:
        sq_pushbool(v, SQFalse);
        break;
      case cJSON_True:
        sq_pushbool(v, SQTrue);
        break;
      case cJSON_NULL:
        sq_pushnull(v);
        break;
      case cJSON_Number:
        if(Item->valueint == Item->valuedouble)
          sq_pushinteger(v, Item->valueint);
        else
          sq_pushfloat(v, Item->valuedouble);
        break;
      case cJSON_String:
        sq_pushstring(v, Item->valuestring, -1);
        break;
      case cJSON_Array:
        sq_newarray(v, 0);
        Sq_DecodeJSONTable(v, Item->child);
        break;
      case cJSON_Object:
        sq_newtable(v);
        Sq_DecodeJSONTable(v, Item->child);
        break;
    }
    if(Item->string)
      sq_newslot(v,-3,SQFalse);
    else
      sq_arrayappend(v, -2);
    Item = Item->next;
  }
}
예제 #20
0
// GetNodePointPos(Node:nodeid,&Float:X,&Float:Y,&Float:Z);
int n_GetNodePointPos(HSQUIRRELVM pVM)
{
	int nodeid;
	sq_getinteger(pVM,-1,&nodeid);
	if(pNodes[nodeid])
	{
		float x,y,z;
		pNodes[nodeid]->GetPos(&x,&y,&z);

		sq_newarray(pVM, 0);
		sq_pushfloat(pVM,x);
		sq_arrayappend(pVM, -2);
		sq_pushfloat(pVM,y);
		sq_arrayappend(pVM, -2);
		sq_pushfloat(pVM,z);
		sq_arrayappend(pVM, -2);
		sq_push(pVM, -1);
		return 1;
	}
	return 0;
}
예제 #21
0
SQInteger CSharedVehicleNatives::GetColour( SQVM * pVM )
{
	// Get the vehicle id
	SQInteger vehicleId;
	sq_getinteger( pVM, -1, &vehicleId );

	// Is the vehicle active?
	if( pCore->GetVehicleManager()->IsActive( vehicleId ) )
	{
		// Get the vehicle colour
		CColor primary, secondary;
		pCore->GetVehicleManager()->Get( vehicleId )->GetColour( &primary, &secondary );

		sq_newarray( pVM, 0 );

		sq_pushinteger( pVM, primary.R );
		sq_arrayappend( pVM, -2 );

		sq_pushinteger( pVM, primary.G );
		sq_arrayappend( pVM, -2 );

		sq_pushinteger( pVM, primary.B );
		sq_arrayappend( pVM, -2 );

		sq_pushinteger( pVM, secondary.R );
		sq_arrayappend( pVM, -2 );

		sq_pushinteger( pVM, secondary.G );
		sq_arrayappend( pVM, -2 );

		sq_pushinteger( pVM, secondary.B );
		sq_arrayappend( pVM, -2 );

		sq_push( pVM, -1 );
		return 1;
	}

	sq_pushbool( pVM, false );
	return 1;
}
예제 #22
0
파일: sqstdstring.cpp 프로젝트: q4a/scourge
static SQInteger _regexp_capture( HSQUIRRELVM v ) {
	SETUP_REX( v );
	const SQChar *str, *begin, *end;
	SQInteger start = 0;
	sq_getstring( v, 2, &str );
	if ( sq_gettop( v ) > 2 ) sq_getinteger( v, 3, &start );
	if ( sqstd_rex_search( self, str + start, &begin, &end ) == SQTrue ) {
		SQInteger n = sqstd_rex_getsubexpcount( self );
		SQRexMatch match;
		sq_newarray( v, 0 );
		for ( SQInteger i = 0;i < n; i++ ) {
			sqstd_rex_getsubexp( self, i, &match );
			if ( match.len > 0 )
				_addrexmatch( v, str, match.begin, match.begin + match.len );
			else
				_addrexmatch( v, str, str, str ); //empty match
			sq_arrayappend( v, -2 );
		}
		return 1;
	}
	return 0;
}
예제 #23
0
// getPickupRotation(Pickupid)
SQInteger CPickupNatives::GetRotation(SQVM * pVM)
{
	SQInteger pickupid;
	sq_getinteger(pVM, 2, &pickupid);
	if(g_pPickupManager->DoesExist(pickupid))
	{
		CVector3 vecPosition;
		if(g_pPickupManager->GetRotation(pickupid, &vecPosition))
		{
			sq_newarray(pVM, 0);
			sq_pushfloat(pVM, vecPosition.fX);
			sq_arrayappend(pVM, -2);
			sq_pushfloat(pVM, vecPosition.fY);
			sq_arrayappend(pVM, -2);
			sq_pushfloat(pVM, vecPosition.fZ);
			sq_arrayappend(pVM, -2);
			return 1;
		}
	}
	sq_pushbool(pVM, false);
	return 1;
}
예제 #24
0
// GetNodeHeader(Node:nodeid,&nodes,&vehicle_nodes,&ped_nodes,&navi_nodes);
int n_GetNodeHeader(HSQUIRRELVM pVM)
{
	int nodeid;
	sq_getinteger(pVM,-1,&nodeid);
	if(pNodes[nodeid])
	{
		int d1 = 0,
			d2 = 0,
			d3 = 0;
		pNodes[nodeid]->GetInfo(&d1,&d2,&d3);

		sq_newarray(pVM, 0);
		sq_pushinteger(pVM,d1);
		sq_arrayappend(pVM, -2);
		sq_pushinteger(pVM,d2);
		sq_arrayappend(pVM, -2);
		sq_pushinteger(pVM,d3);
		sq_arrayappend(pVM, -2);
		sq_push(pVM, -1);
		return 1;
	}
	return 0;
}
예제 #25
0
static SQInteger _string_split(HSQUIRRELVM v)
{
	const SQChar *str,*seps;
	SQChar *stemp;
	sq_getstring(v,2,&str);
	sq_getstring(v,3,&seps);
	SQInteger sepsize = sq_getsize(v,3);
	if(sepsize == 0) return sq_throwerror(v,_SC("empty separators string"));
	SQInteger memsize = (sq_getsize(v,2)+1)*sizeof(SQChar);
	stemp = sq_getscratchpad(v,memsize);
	memcpy(stemp,str,memsize);
	SQChar *start = stemp;
	SQChar *end = stemp;
	sq_newarray(v,0);
	while(*end != '\0')
	{
		SQChar cur = *end;
		for(SQInteger i = 0; i < sepsize; i++)
		{
			if(cur == seps[i])
			{
				*end = 0;
				sq_pushstring(v,start,-1);
				sq_arrayappend(v,-2);
				start = end + 1;
				break;
			}
		}
		end++;
	}
	if(end != start)
	{
		sq_pushstring(v,start,-1);
		sq_arrayappend(v,-2);
	}
	return 1;
}
예제 #26
0
// arr TwQueryTween(HANDLE hTween)
SQInteger TwQueryTween(HSQUIRRELVM v)
{
	SQInteger          nargs         = sq_gettop(v);
	SQBool             bRet          = FALSE;
	SQInteger          nTween        = NULL;
	Tweener*           pTweener      = NULL;
	std::vector<TweenerProperty> arrProperties;
	std::vector<TweenerProperty>::iterator it;

	if (!v || 1 + 1 != nargs) {goto _Exit_;}
	if (OT_INTEGER != sq_gettype(v, 2)) {goto _Exit_;}

	sq_getinteger(v, 2, &nTween);

	pTweener = (Tweener*)QiHwHandleToObj(nTween);
	if (!pTweener) {goto _Exit_;}

	pTweener->QueryTween(0, arrProperties);
	if (arrProperties.empty()) {goto _Exit_;}

	sq_newarray(v, 0/*arrProperties.size()*/);

	for (it = arrProperties.begin(); it != arrProperties.end(); ++it ) {
		sq_pushinteger(v, it->curValue);
		sq_arrayappend(v,-2);
	}

	bRet = TRUE;

_Exit_:
	if (!bRet) {
		sq_pushnull(v);
	}

	return 1;
}
예제 #27
0
bool CSquirrelArgument::push(SQVM * pVM)
{
	switch(type)
	{
		case OT_NULL:
			sq_pushnull(pVM);
			break;
		case OT_INTEGER:
			sq_pushinteger(pVM, data.i);
			break;
		case OT_BOOL:
			sq_pushbool(pVM, data.b);
			break;
		case OT_FLOAT:
			sq_pushfloat(pVM, data.f);
			break;
		case OT_STRING:
			sq_pushstring(pVM, data.str->Get(), data.str->GetLength());
			break;
		case OT_ARRAY:
			{
				sq_newarray(pVM, 0);

				for(CSquirrelArguments::iterator iter = data.pArray->begin(); iter != data.pArray->end(); iter++)
				{
					(*iter)->push(pVM);
					sq_arrayappend(pVM, -2);
				}

				break;
			}
		case OT_TABLE:
			{
				assert(data.pArray->size() % 2 == 0);
				sq_newtable(pVM);

				for(CSquirrelArguments::iterator iter = data.pArray->begin(); iter != data.pArray->end(); iter++)
				{
					(*iter)->push(pVM);
					++iter;
					(*iter)->push(pVM);
					sq_createslot(pVM, -3);
				}

				break;
			}
			break;
		case OT_CLOSURE:
		case OT_NATIVECLOSURE:
			sq_pushobject(pVM, data.sqObject);
			break;
		case OT_INSTANCE:
			{
				SQObject obj;
				obj._type = OT_INSTANCE;
				obj._unVal.pInstance = data.pInstance;
				sq_pushobject(pVM, obj);
			}
			break;
		default:
			sq_pushnull(pVM); // whatsoever. do not even care. fix it if you dare.
			assert(0);
			return false;
	}

	return true;
}
예제 #28
0
파일: main.cpp 프로젝트: ruifig/nutcracker
int main (int argc, char** argv)
{
	ENABLE_LEAK_CHECK();

#if defined(SHELL_PLATFORM_WINDOWS)
	SetConsoleTitle("Squirrel Shell " SHELL_VERSION_STR " (" SHELL_CPUARCH ")");
#else
	stderrIsRedirected = !isatty(2);
#endif

	// Parse command line arguments.
	const char* fileName	= NULL;
	bool		interactive = argc == 1;
	int			firstArg	= 0,
				i;
	bool isDebug = false;
	int debuggerPort = 0;
	for (i = 1; argv[i]; ++i)
	{
		char* arg = argv[i];

		if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
		{
			printf("Squirrel Shell %s for %s on %s (" __DATE__ ")\n"
				   SHELL_VERSION_COPYRIGHT "\n"
				   "\n"
				   "This is free software, and comes WITHOUT ANY WARRANTY; without even the implied\n"
				   "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
				   "General Public License for more details.\n"
				   "\n"
				   "MD5 hash calculation code (c) Colin Plumb\n"
				   "PCRE (c) University of Cambridge\n"
				   "Squirrel (c) Alberto Demichelis\n"
				   "zlib (c) Jean-loup Gailly and Mark Adler\n"
				   "\n"
				   "Usage:\n"
				   "   squirrelsh [options] [script_file] [script_arguments]\n"
				   "\n"
				   "Options:\n"
				   "   -h, --help          Display this text\n"
				   "   -d<PORT>            Enable the debugger, in the specified port\n"
				   "   -i, --interactive   Run shell in interactive mode\n"
				   "                       If script file is specified, it will be executed before\n"
				   "                       entering this mode\n"
				   "   -s, --silent        Do not display error and warning messages\n"
				   "   -v, --version       Display shell version number\n"
				   "\n"
				   "Examples:\n"
				   "   squirrelsh                    Run shell in interactive mode\n"
				   "   squirrelsh foo.nut            Run foo.nut script without arguments\n"
				   "   squirrelsh -i foo.nut 1 2 3   Run foo.nut script with arguments \"1\", \"2\"\n"
				   "                                 and \"3\", and switch into interactive mode\n",
				   SHELL_VERSION_STR,
				   SHELL_PLATFORM,
				   SHELL_CPUARCH);

			return EXIT_SUCCESS;
		}
		else if (!strncmp(arg, "-d", 2))
		{
			// RVF +
			isDebug = true;
			debuggerPort = std::atoi(arg + 2);
			if (debuggerPort == 0)
			{
				printf("No debugger port specified\n");
				return EXIT_FAILURE;
			}
			// RVF -
		}
		else if (!strcmp(arg, "-i") || !strcmp(arg, "--interactive"))
			interactive = true;
		else if (!strcmp(arg, "-v") || !strcmp(arg, "--version"))
		{
			printf("%s\n", SHELL_VERSION_STR);
			return EXIT_SUCCESS;
		}
		else if (!strcmp(arg, "-s") || !strcmp(arg, "--silent"))
			silent = true;
		else
		{
			// First unreserved argument will be treated as script file name.
			fileName = arg;
			firstArg = i;
			break;
		}
	}

	if (!fileName && !interactive)
	{
		PrintError("ERROR: Script file not specified.\n");
		return EXIT_FAILURE;
	}

	// Initialize Squirrel.
	sqvm = sq_open(1024);
	if (!sqvm)
	{
		PrintError("ERROR: Failed to create Squirrel VM.\n");
		return EXIT_FAILURE;
	}

	sqstd_seterrorhandlers(sqvm);

	HSQREMOTEDBG rdbg = nullptr;
	if (isDebug)
	{
		rdbg = sq_rdbg_init(sqvm, debuggerPort, SQTrue);
		sq_enabledebuginfo(sqvm, SQTrue);

		//!! SUSPENDS THE APP UNTIL THE DEBUGGER CLIENT CONNECTS
		scprintf("Waiting for the debugger to connect...\n");
		if (!SQ_SUCCEEDED(sq_rdbg_waitforconnections(rdbg)))
		{
			PrintError("ERROR: Failed to connect to the debugger.\n");
			return EXIT_FAILURE;
		}
		scprintf(_SC("Connected to the debugger\n"));
	}


	//sq_setcompilererrorhandler(sqvm, SquirrelCompileError);

	_RPT0(_CRT_WARN, "--- Squirrel initialized\n");

	// Register some globals.
	SetSqString("SHELL_VERSION", SHELL_VERSION_STR, SQTrue);
	SetSqString("SQUIRREL_VERSION", SQUIRREL_VERSION_SHORT, SQTrue);
	SetSqString("PLATFORM", SHELL_PLATFORM, SQTrue);
	SetSqString("CPU_ARCH", SHELL_CPUARCH, SQTrue);

	// Initialize libraries.
	Init_Base();
	Init_IO();
	Init_File();
	Init_Math();
	Init_Util();
	Init_Hash();
	Init_RegExp();

	_RPT0(_CRT_WARN, "--- Libraries initialized\n");

	// Set up global variables...
	sq_pushroottable(sqvm);

	// RVF +
	// Initialize squirrel std libraries
	//sqstd_register_bloblib(sqvm);
	sqstd_register_iolib(sqvm); // We need this one because of the handy "dofile" function
	sqstd_register_stringfunctions(sqvm); // This registers only some string functions that are useful and don't clash with Squirrel Shell
	// NOTE: Not registering the other libraries, because there are name clashing between Squirrel Shell and SqStdLib
	//sqstd_register_systemlib(sqvm);
	//sqstd_register_mathlib(sqvm);
	//sqstd_register_stringlib(sqvm);
	// RVF -


	// ... number of command line arguments...
	sq_pushstring(sqvm, "__argc", -1);
	sq_pushinteger(sqvm, SQInteger(argc - firstArg));
	if (SQ_FAILED(sq_newslot(sqvm, -3, SQFalse)))
	{
		PrintError("ERROR: Failed to create \"__argc\" integer value.\n");
		Shutdown();
		return EXIT_FAILURE;
	}

	// ... and arguments themselves.
	sq_pushstring(sqvm, "__argv", -1);
	sq_newarray(sqvm, 0);
	for (i = firstArg; argv[i]; ++i)
	{
		sq_pushstring(sqvm, argv[i], -1);
		sq_arrayappend(sqvm, -2);
	}
	if (SQ_FAILED(sq_newslot(sqvm, -3, SQFalse)))
	{
		PrintError("ERROR: Failed to create \"__argv\" array.\n");
		Shutdown();
		return EXIT_FAILURE;
	}
	sq_pop(sqvm, 1);

	// Load and run script.
	SQInteger result = EXIT_SUCCESS;
	if (fileName && LoadScript(fileName))
	{
		sq_pushroottable(sqvm);
		if (SQ_FAILED(sq_call(sqvm, 1, SQTrue, isDebug ? SQTrue : SQFalse)))
		{
			if (!silent)
			{
				const SQChar* errMsg = "Unknown error.";
				sq_getlasterror(sqvm);
				if (sq_gettype(sqvm, -1) == OT_STRING)
					sq_getstring(sqvm, -1, &errMsg);

				PrintError("ERROR: %s\n", errMsg);
			}
			Shutdown();
			return EXIT_FAILURE;
		}

		// Get script execution result.
		if (sq_getvmstate(sqvm) == SQ_VMSTATE_SUSPENDED)
			result = retCode;
		else
		{
			if (sq_gettype(sqvm, -1) == OT_INTEGER)
				sq_getinteger(sqvm, -1, &result);
		}

		// Pop everything except root table.
		sq_settop(sqvm, 1);
	}

	// Enter interactive mode (if necessary).
	if (interactive)
	{
		SQChar cmd[MAX_CMD_LENGTH + 1];
		do
		{
#if defined(SHELL_PLATFORM_WINDOWS)
			GetCurrentDirectory(sizeof(cmd), cmd);
#else
			getcwd(cmd, sizeof(cmd));
#endif
			cmd[sizeof(cmd) - 1] = 0;

			printf("%s> ", ConvPath(cmd, SQFalse));
			fgets(cmd, MAX_CMD_LENGTH, stdin);
			if (SQ_FAILED(sq_compilebuffer(sqvm, cmd, SQInteger(strlen(cmd)), "", SQTrue)))
				continue;

			sq_pushroottable(sqvm);
			if (SQ_FAILED(sq_call(sqvm, 1, SQFalse, SQFalse)) && !silent)
			{
				const SQChar* errMsg = "Unknown error.";
				sq_getlasterror(sqvm);
				if (sq_gettype(sqvm, -1) == OT_STRING)
					sq_getstring(sqvm, -1, &errMsg);

				PrintError("ERROR: %s\n", errMsg);
			}
		} while(sq_getvmstate(sqvm) != SQ_VMSTATE_SUSPENDED);
		result = retCode;
	}

	if (isDebug)
	{
		sq_rdbg_shutdown(rdbg);
	}

	Shutdown();
	return int(result);
}
예제 #29
0
char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p)
{
	SKIP_EMPTY(p);

	if (strncmp(p, "false", 5) == 0) {
		sq_pushinteger(vm, 0);
		return p + 5;
	}
	if (strncmp(p, "true", 4) == 0) {
		sq_pushinteger(vm, 1);
		return p + 4;
	}
	if (strncmp(p, "null", 4) == 0) {
		sq_pushnull(vm);
		return p + 4;
	}

	switch (*p) {
		case '"': {
			/* String */
			p = ReadString(vm, ++p);
			if (p == NULL) return NULL;

			break;
		}

		case '{': {
			/* Table */
			p = this->ReadTable(vm, p);
			if (p == NULL) return NULL;

			break;
		}

		case '[': {
			/* Array */
			sq_newarray(vm, 0);

			/* Empty array? */
			char *p2 = p+1;
			SKIP_EMPTY(p2);
			if (*p2 == ']') {
				p = p2+1;
				break;
			}

			while (*p++ != ']') {
				p = this->ReadValue(vm, p);
				if (p == NULL) {
					sq_pop(vm, 1);
					return NULL;
				}
				sq_arrayappend(vm, -2);

				SKIP_EMPTY(p);
				if (*p == ',') continue;
				if (*p == ']') break;
				RETURN_ERROR(1);
			}

			p++;

			break;
		}

		case '1': case '2': case '3': case '4': case '5':
		case '6': case '7': case '8': case '9': case '0':
		case '-': {
			/* Integer */

			const char *value = p++;
			for (;;) {
				switch (*p++) {
					case '1': case '2': case '3': case '4': case '5':
					case '6': case '7': case '8': case '9': case '0':
						continue;

					default:
						break;
				}

				p--;
				break;
			}

			int res = atoi(value);
			sq_pushinteger(vm, (SQInteger)res);

			break;
		}

		default:
			RETURN_ERROR(0);
	}

	return p;
}
예제 #30
0
/*
** Copies values from State src to State dst.
*/
static SQRESULT copy_values_between_vms (HSQUIRRELVM dst, HSQUIRRELVM src, int argc, int argIdx)
{
    SQRESULT _rc_;
    sq_reservestack(dst, argc + 20);
    argc += argIdx; //we will work with argc args starting at argIdx
    for (; argIdx < argc; argIdx++)
    {
        switch (sq_gettype(src, argIdx))
        {
        case OT_INTEGER:
            SQ_GET_INTEGER(src, argIdx, vint);
            sq_pushinteger(dst, vint);
            break;

        case OT_FLOAT:
            SQ_GET_FLOAT(src, argIdx, vfloat);
            sq_pushfloat (dst, vfloat);
            break;

        case OT_BOOL:
            SQ_GET_BOOL(src, argIdx, vbool);
            sq_pushbool (dst, vbool);
            break;

        case OT_STRING:
        {
            SQ_GET_STRING(src, argIdx, vstr)
            sq_pushstring (dst, vstr, vstr_size);
        }
        break;

        case OT_ARRAY:
        {
            SQInteger size = sq_getsize(src, argIdx);
            sq_newarray(dst, size);
            for(SQInteger i=0; i<size; ++i)
            {
                sq_pushinteger(src, i);
                sq_get(src, -2);
                sq_pushinteger(dst, i);
                if(copy_values_between_vms(dst, src, 1, sq_gettop(src)) != SQ_OK) return SQ_ERROR;
                sq_poptop(src);
                sq_set(dst, -3);
            }
        }
        break;

        case OT_TABLE:
        {
            sq_newtable(dst);
            sq_pushnull(src);
            while(sq_next(src, -2) == SQ_OK)
            {
                SQInteger src_top = sq_gettop(src);
                if(copy_values_between_vms(dst, src, 1, src_top-1) != SQ_OK
                        || copy_values_between_vms(dst, src, 1, src_top) != SQ_OK) return SQ_ERROR;
                sq_newslot(dst, -3, SQFalse);
                sq_pop(src, 2);
            }
            sq_pop(src,1);
        }
        break;

        case OT_USERPOINTER:
        {
            SQUserPointer ptr;
            sq_getuserpointer(src, argIdx, &ptr);
            sq_pushuserpointer(dst, ptr);
        }
        break;

        case OT_NULL:
            sq_pushnull(dst);
            break;

        default:
            return SQ_ERROR;
        }
    }
    return SQ_OK;
}