Форум Flasher.ru
Ближайшие курсы в Школе RealTime
Список интенсивных курсов: [см.]  
  
Специальные предложения: [см.]  
  
 
Блоги Правила Справка Пользователи Календарь Поиск рулит! Сообщения за день Все разделы прочитаны
 

Вернуться   Форум Flasher.ru > Flash > ActionScript 3.0

Версия для печати  Отправить по электронной почте    « Предыдущая тема | Следующая тема »  
Опции темы Опции просмотра
 
Создать новую тему Ответ
Старый 07.12.2011, 19:15
Aquahawk вне форума Посмотреть профиль Отправить личное сообщение для Aquahawk Посетить домашнюю страницу Aquahawk Найти все сообщения от Aquahawk
  № 11  
Ответить с цитированием
Aquahawk
 
Аватар для Aquahawk

Регистрация: Nov 2010
Адрес: Москва
Сообщений: 915
Записей в блоге: 4
Отправить сообщение для Aquahawk с помощью ICQ Отправить сообщение для Aquahawk с помощью Skype™
кстати, объявлен инт вот так
Код AS3:
public final class int extends Object
и каким макаром он оказывается is Number мне не понятно.
Намбер
Код AS3:
public final class Number extends Object
Видимо оператор is работает для них как-то по особому. В документации про него написано достаточно размыто.

Ещё немного теста

Код AS3:
var a:Number = 5;
trace("a is int:", a is int);
trace("a is Number:", a is Number);
trace("typeof(a):", typeof(a));
trace("a[\"constructor\"]:", a["constructor"]);
trace("a instanceof int:", a instanceof int);
trace("a instanceof Number:", a instanceof Number);
trace("describeType(a)", describeType(a));
 
trace("-------------------");
 
var b:int = 5;
trace("b is int:", b is int);
trace("b is Number:", b is Number);
trace("typeof(b):", typeof(b));
trace("b[\"constructor\"]:", b["constructor"]);
trace("b instanceof int:", b instanceof int);
trace("b instanceof Number:", b instanceof Number);
trace("describeType(b)", describeType(b));
Код AS3:
a is int: true
a is Number: true
typeof(a): number
a["constructor"]: [class Number]
a instanceof int: false
a instanceof Number: true
describeType(a) <type name="int" base="Object" isDynamic="false" isFinal="true" isStatic="false">
  <extendsClass type="Object"/>
  <constructor>
    <parameter index="1" type="*" optional="true"/>
  </constructor>
</type>
-------------------
b is int: true
b is Number: true
typeof(b): number
b["constructor"]: [class Number]
b instanceof int: false
b instanceof Number: true
describeType(b) <type name="int" base="Object" isDynamic="false" isFinal="true" isStatic="false">
  <extendsClass type="Object"/>
  <constructor>
    <parameter index="1" type="*" optional="true"/>
  </constructor>
</type>
Добавлено через 2 минуты
Код AS3:
Alex Lexcuk
В инте 31 значащий бит, в uint 32, а в Number 53, правда не понятно со знаком или нет. Понятно поему у вас это происходило.

Добавлено через 4 минуты
если в
Код AS3:
a
записать 5.5 например, то там будет уже намбер.
Код AS3:
var a:Number = 5.5;
trace("a is int:", a is int);
trace("a is Number:", a is Number);
trace("typeof(a):", typeof(a));
trace("a[\"constructor\"]:", a["constructor"]);
trace("a instanceof int:", a instanceof int);
trace("a instanceof Number:", a instanceof Number);
trace("describeType(a)", describeType(a));
Код AS3:
a is int: false
a is Number: true
typeof(a): number
a["constructor"]: [class Number]
a instanceof int: false
a instanceof Number: true
describeType(a) <type name="Number" base="Object" isDynamic="false" isFinal="true" isStatic="false">
  <extendsClass type="Object"/>
  <constructor>
    <parameter index="1" type="*" optional="true"/>
  </constructor>
</type>
Добавлено через 10 минут
как бы в исходниках тамарина найти как is организован, на досуге может пороюсь. Буду благодарен если кто подскажет как удобно ориентироваться в исходниках тамарина
__________________
:)

Старый 07.12.2011, 19:32
alatar вне форума Посмотреть профиль Отправить личное сообщение для alatar Найти все сообщения от alatar
  № 12  
Ответить с цитированием
alatar
 
Аватар для alatar

блогер
Регистрация: Dec 2008
Адрес: Israel, Natanya
Сообщений: 4,740
Записей в блоге: 11
Простые типы вообще особняком стоят, по сравнению с остальными объектами. Фактически, согласно документации, они передаются по ссылке, но при первом удобном случае пытаются скопироваться по значению. Между собой они тоже сравниваются по значению.
Зачем вообще такие тонкости? Попалась задача, где существенна разница между int и Number.
Цитата:
Буду б лагодарен если кто подскажет как удобно ориентироваться в исходниках тамарина
Скачать их себе и ориентироваться
__________________
משיח לא בא
משיח גם לא מטלפן


Последний раз редактировалось alatar; 07.12.2011 в 19:37.
Старый 07.12.2011, 19:45
i.o. вне форума Посмотреть профиль Отправить личное сообщение для i.o. Найти все сообщения от i.o.
  № 13  
Ответить с цитированием
i.o.
 
Аватар для i.o.

Регистрация: Apr 2010
Адрес: Earth
Сообщений: 1,897
Код AS3:
    [native(cls="NumberClass", instance=<b>"double"b>, methods="auto")]
    public final class Number 
    {
    ...
Код AS3:
    [native(cls="IntClass", instance=<b>"int32_t"b>, methods="auto")]
    public final class int
    {
        // based on Number: E262 {ReadOnly, DontDelete, DontEnum}
        public static const MIN_VALUE:int = -0x80000000;
        public static const MAX_VALUE:int =  0x7fffffff;
    ...
double и int32_t как бы намекают на истинную природу вещей.
Правда смущает коментарий к int - "based on Number"

Старый 07.12.2011, 19:45
Aquahawk вне форума Посмотреть профиль Отправить личное сообщение для Aquahawk Посетить домашнюю страницу Aquahawk Найти все сообщения от Aquahawk
  № 14  
Ответить с цитированием
Aquahawk
 
Аватар для Aquahawk

Регистрация: Nov 2010
Адрес: Москва
Сообщений: 915
Записей в блоге: 4
Отправить сообщение для Aquahawk с помощью ICQ Отправить сообщение для Aquahawk с помощью Skype™
Да именно, попалась задача где разница существенна.

Добавлено через 3 минуты
i.o. а откуда это?
Я в тамарине вижу
Код AS3:
[native(cls="NumberClass", instance="double", methods="auto")]
public final class Number
и
Код AS3:
[native(cls="IntClass", instance="int32_t", methods="auto")]
public final class int
и
Код AS3:
[native(cls="UIntClass", instance="uint32_t", methods="auto")]
public final class uint
__________________
:)

Старый 07.12.2011, 19:52
i.o. вне форума Посмотреть профиль Отправить личное сообщение для i.o. Найти все сообщения от i.o.
  № 15  
Ответить с цитированием
i.o.
 
Аватар для i.o.

Регистрация: Apr 2010
Адрес: Earth
Сообщений: 1,897
tamarin-central-fbecf6c8a86f\core\Number.as
Код AS3:
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2004-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
 
 
package
{
	[native(cls="NumberClass", instance="double", methods="auto")]
	public final class Number 
	{
		// Number.length = 1 per ES3
		// E262 {ReadOnly, DontDelete, DontEnum }
		public static const length:int = 1
 
		// E262 {DontEnum, DontDelete, ReadOnly}
		public static const NaN               :Number = 0/0
		public static const NEGATIVE_INFINITY :Number = -1/0
		public static const POSITIVE_INFINITY :Number = 1/0
		public static const MIN_VALUE         :Number = 4.9e-324 
		public static const MAX_VALUE         :Number = 1.7976931348623158e+308
 
		// these must match the same constants in MathUtils
		private static const DTOSTR_FIXED:int = 1
		private static const DTOSTR_PRECISION:int = 2
		private static const DTOSTR_EXPONENTIAL:int = 3
 
		private static native function _numberToString(n:Number, radix:int):String
		private static native function _convert(n:Number, precision:int, mode:int):String
 
		AS3 function toString(radix=10):String {
			return _numberToString(this,radix)
		}
		AS3 function valueOf():Number { return this }
 
		prototype.toLocaleString = 
		prototype.toString = function (radix=10):String
		{
			if (this === prototype) return "0"
 
			if (!(this is Number))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "Number.prototype.toString" );
 
			return _numberToString(this, radix)
		}
 
		prototype.valueOf = function()
		{
			if (this === prototype)	return 0
			if (!(this is Number))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "Number.prototype.valueOf" );
			return this;
		}
 
		AS3 function toExponential(p=0):String
		{
			return _convert(this, int(p), DTOSTR_EXPONENTIAL)
		}
		prototype.toExponential = function(p=0):String
		{
			return _convert(Number(this), int(p), DTOSTR_EXPONENTIAL)
		}
 
		AS3 function toPrecision(p=0):String
		{
			if (p == undefined)
				return this.toString();
 
			return _convert(this, int(p), DTOSTR_PRECISION)
		}
		prototype.toPrecision = function(p=0):String
		{
			if (p == undefined)
				return this.toString();
 
			return _convert(Number(this), int(p), DTOSTR_PRECISION)
		}
 
		AS3 function toFixed(p=0):String
		{
			return _convert(this, int(p), DTOSTR_FIXED)
		}
		prototype.toFixed = function(p=0):String
		{
			return _convert(Number(this), int(p), DTOSTR_FIXED)
		}
 
        // Dummy constructor function - This is neccessary so the compiler can do arg # checking for the ctor in strict mode
        // The code for the actual ctor is in NumberClass::construct in the avmplus
        public function Number(value = 0)
        {}
 
		_dontEnumPrototype(prototype);
	}
 
	[native(cls="IntClass", instance="int32_t", methods="auto")]
	public final class int
	{
		// based on Number: E262 {ReadOnly, DontDelete, DontEnum}
		public static const MIN_VALUE:int = -0x80000000;
		public static const MAX_VALUE:int =  0x7fffffff;
 
		// Number.length = 1 per ES3
		// E262 {ReadOnly, DontDelete, DontEnum }
		public static const length:int = 1
 
		AS3 function toString(radix=10):String {
			return Number(this).AS3::toString(radix)
		}
		AS3 function valueOf():int { return this }
 
		prototype.toLocaleString =
		prototype.toString = function toString(radix=10):String
		{
			if (this === prototype) return "0"
			if (!(this is int))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "int.prototype.toString" );
			return Number(this).toString(radix)
		}
 
		prototype.valueOf = function()
		{
			if (this === prototype) return 0
			if (!(this is int))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "int.prototype.valueOf" );
			return this
		}
 
		AS3 function toExponential(p=0):String
		{
			return Number(this).AS3::toExponential(p)
		}
		prototype.toExponential = function(p=0):String
		{
			return Number(this).AS3::toExponential(p)
		}
 
		AS3 function toPrecision(p=0):String
		{
			return Number(this).AS3::toPrecision(p)
		}
		prototype.toPrecision = function(p=0):String
		{
			return Number(this).AS3::toPrecision(p)
		}
 
		AS3 function toFixed(p=0):String
		{
			return Number(this).AS3::toFixed(p)
		}
		prototype.toFixed = function(p=0):String
		{
			return Number(this).AS3::toFixed(p)
		}
 
        // Dummy constructor function - This is neccessary so the compiler can do arg # checking for the ctor in strict mode
        // The code for the actual ctor is in IntClass::construct in the avmplus
        public function int(value = 0)
        {}
 
		_dontEnumPrototype(prototype);		
	}
 
	[native(cls="UIntClass", instance="uint32_t", methods="auto")]
	public final class uint
	{
		// based on Number: E262 {ReadOnly, DontDelete, DontEnum}
		public static const MIN_VALUE:uint = 0;
		public static const MAX_VALUE:uint = 0xffffffff;
 
		// Number.length = 1 per ES3
		// E262 {ReadOnly, DontDelete, DontEnum}
		public static const length:int = 1
 
		AS3 function toString(radix=10):String {
			return Number(this).AS3::toString(radix)
		}
		AS3 function valueOf():uint { return this }
 
		prototype.toLocaleString =
		prototype.toString = function toString(radix=10):String
		{
			if (this === prototype) return "0"
			if (!(this is Number))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "uint.prototype.toString" );
			return Number(this).toString(radix)
		}
 
		prototype.valueOf = function()
		{
			if (this === prototype) return 0
			if (!(this is uint))
				Error.throwError( TypeError, 1004 /*kInvokeOnIncompatibleObjectError*/, "uint.prototype.valueOf" );
			return this
		}
 
		AS3 function toExponential(p=0):String
		{
			return Number(this).AS3::toExponential(p)
		}
		prototype.toExponential = function(p=0):String
		{
			return Number(this).AS3::toExponential(p)
		}
 
		AS3 function toPrecision(p=0):String
		{
			return Number(this).AS3::toPrecision(p)
		}
		prototype.toPrecision = function(p=0):String
		{
			return Number(this).AS3::toPrecision(p)
		}
 
		AS3 function toFixed(p=0):String
		{
			return Number(this).AS3::toFixed(p)
		}
		prototype.toFixed = function(p=0):String
		{
			return Number(this).AS3::toFixed(p)
		}
 
        // Dummy constructor function - This is neccessary so the compiler can do arg # checking for the ctor in strict mode
        // The code for the actual ctor is in UIntClass::construct in the avmplus
        public function uint(value = 0)
        {}
 
		_dontEnumPrototype(prototype);
	}
}

Старый 07.12.2011, 20:05
Aquahawk вне форума Посмотреть профиль Отправить личное сообщение для Aquahawk Посетить домашнюю страницу Aquahawk Найти все сообщения от Aquahawk
  № 16  
Ответить с цитированием
Aquahawk
 
Аватар для Aquahawk

Регистрация: Nov 2010
Адрес: Москва
Сообщений: 915
Записей в блоге: 4
Отправить сообщение для Aquahawk с помощью ICQ Отправить сообщение для Aquahawk с помощью Skype™
блин привиделось, я в этом сообщении во второй цитате увидел
Код AS3:
[native(cls="IntClass", instance=<b>"int32_t"b>, methods="auto")]
    public final class Number
    {
        // based on Number: E262 {ReadOnly, DontDelete, DontEnum}
        public static const MIN_VALUE:int = -0x80000000;
        public static const MAX_VALUE:int =  0x7fffffff;
__________________
:)

Старый 07.12.2011, 20:15
in4core вне форума Посмотреть профиль Отправить личное сообщение для in4core Найти все сообщения от in4core
  № 17  
Ответить с цитированием
in4core
[+4 06.05.14]
 
Аватар для in4core

Регистрация: Mar 2009
Сообщений: 4,219
Записей в блоге: 14
Ну а собственно что не так? Слово Number - есть число. int / uint тоже число. А теперь представим такую ситуацию, что var a:* = 10 ( a is int , a is uint , a is Number ) - все да. Но объединяет их всех все равно же Number - тоесть число. Другой вопрос как это организовано раз в исходниках перевода нет. С другой стороны, какая разница то? Что вам дадут эти проверки...
__________________
Марк Tween

Старый 08.12.2011, 00:51
wvxvw вне форума Посмотреть профиль Отправить личное сообщение для wvxvw Найти все сообщения от wvxvw
  № 18  
Ответить с цитированием
wvxvw
Modus ponens
 
Аватар для wvxvw

модератор форума
Регистрация: Jul 2006
Адрес: #1=(list #1#)
Сообщений: 8,049
Записей в блоге: 38
Вобщем-то базисные типы живут по своим законам, и для них определены неявные правила приведения, а для пользовательских типов такой возможности нету. Описание ES требует, чтобы типы int, uint и Number были взаимозаменимы, поэтому используется Number - т.как может вместить любой из трех типов, а когда известен тип в месте применения, к значению применяется функция переводящая в нужный тип. Но эти правила имеют значение только на этапе написания кода, т.как JIT будет по своему усмотрению переводить в конкретные машинные инструкции и данные.

Но если быть до конца отрковенным... то отношения между численными типами в AS3 не подчиняются никакой логике... т.е. в какой-то момент стало очевидно, что можно легко реализвоать API для оптимизации определенных операций, и поэтому добавили 2 новых типа к одному старому "универсальному". А так, ни с математической, ни с практической точки зрения система и не полная и не последовательная...
__________________
Hell is the possibility of sanity

Старый 08.12.2011, 11:44
smithy вне форума Посмотреть профиль Отправить личное сообщение для smithy Найти все сообщения от smithy
  № 19  
Ответить с цитированием
smithy

Регистрация: Oct 2011
Адрес: Питер
Сообщений: 58
Интересно было бы в исходниках тамарина найти реализацию оператора is и посмотреть почему он возвращает такие результаты.

Старый 08.12.2011, 13:02
Aquahawk вне форума Посмотреть профиль Отправить личное сообщение для Aquahawk Посетить домашнюю страницу Aquahawk Найти все сообщения от Aquahawk
  № 20  
Ответить с цитированием
Aquahawk
 
Аватар для Aquahawk

Регистрация: Nov 2010
Адрес: Москва
Сообщений: 915
Записей в блоге: 4
Отправить сообщение для Aquahawk с помощью ICQ Отправить сообщение для Aquahawk с помощью Skype™
Они всё-таки отличаются!
Код AS3:
a = NaN;
b = NaN;
trace(a, b);
Код AS3:
NaN 0
То что было объявлено как намбер может хранить NaN а инт не может.
__________________
:)

Создать новую тему Ответ Часовой пояс GMT +4, время: 19:22.
Быстрый переход
  « Предыдущая тема | Следующая тема »  
Опции темы
Опции просмотра

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.


 


Часовой пояс GMT +4, время: 19:22.


Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2024, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.