Haxe: Function argument that matches an interface - interface

I have a method (in Haxe) that needs to accept any object that has a 'width' and 'height' property. I'm assuming that I can do that somehow with an Interface, but for my purposes the object that is passed in does not need to implement the interface, it just needs to be any object with a width and height property.
This does not work, as the object you pass in needs to implement interface:
Interface IWidthAndHeight{
public var width : Float;
public var height : Float;
}
Class Main{
var o : IWidthAndHeight;
public function setObject( o : IWidthAndHeight ){
this.o = o;
}
}
Currently I am using Dynamic, and manually cheking that the properties exist, but is there a smarter way? Current method:
Class Main{
var o : Dynamic;
public function setObject( o : Dynamic ){
if (propertiesExist(o,['width','height'])){
this.o = o;
}
}
// Note: propertiesExist is my own method. Just assume it works :)
}
Any help appreciated. Thanks!

You can use anonymous structures here:
typedef WidthAndHeight = {
width:Float,
height:Float
}
class Main {
var o:WidthAndHeight;
public function setObject(o:WidthAndHeight) {
this.o = o;
}
}
This is just alternative to var o:{width:Float, height:Float}; with typedef.
Any class or structure in setObject argument will be checked for these fields in compile time, this is called structural subtyping.

Related

Using templates to rewrite polymorphic class to one single class (compile time polymorphism)

In my current code I use runtime polymorphism to create different subtypes of "light" from a LightBase class. The lighttypes however are already known at compile time (preprocessor picks the right variant). So I figured it is really not the right tool to do so as it is slow (vtable lookup for virtual getter functions) and could be already done at compile time. I just don't know how... could it be done with templates? I don't have too much experience in template programming so I don't know what is possible.
Essentially I want to instantiate a subclass of either type NormalLight or SpecialLight which have the same functions as LightBase but operate on a different set of constants:
class Color
{
Color(std::string color_name) : color_name_(color_name) { }
private:
std::string color_name_;
}
class LightBase {
public:
std::unique_ptr& GetInstance() { return instance_; }
protected:
const resolution;
std::array<Color, 0> = { };
// ..
private:
static std::unique_ptr<LightBase> instance_;
}
class NormalLight : public LightBase
{
protected:
const resolution = 9;
std::array<Color, 3> { Color("blue"), Color("red"), Color("purple") };
// ..
}
class SpecialLight : public LightBase
{
protected:
const resolution = 13;
std::array<Color, 3> { Color("yellow"), Color("magenta"), Color("orange") };
// ..
}
#if defined CONFIG_LIGHT_TYPE_NORMAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<NormalLight>(new NormalLight());
#elif defined CONFIG_LIGHT_TYPE_SPECIAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<SpecialLight>(new SpecialLight());
#endif
In a function I could conditionally check for a template parameter (I guess) but it's a class definition. Also, the thing should compile in C++11. Any ideas?

Find direct & indirect method usages if method is overriden in base class

please, help me to figure out how to write the query :)
The code is:
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var man = new Man("Joe");
Console.WriteLine(man.ToString());
}
}
public class SuperMan
{
public SuperMan(string name)
{
this.name = name;
}
public override string ToString()
{
return name;
}
string name;
}
public class Man : SuperMan
{
public Man(string name) : base(name)
{
}
}
}
I want to find all direct and indirect dependencies (methods) to Man.ToString(). There is only one call in Main() method.
The query I'm trying is:
from m in Methods
let depth0 = m.DepthOfIsUsing("ConsoleApplication1.SuperMan.ToString()")
where depth0 >= 0 orderby depth0
select new { m, depth0 }.
but it doesn't find dependent Program.Main() method....
How to modify query so that it finds usages for such kind of methods?
First let's look at direct callers. We want to list all methods that calls SuperMan.ToString() or any ToString() methods overriden by SuperMan.ToString(). It can looks like:
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
from m in Application.Methods.UsingAny(baseMethods)
where m.IsUsing("ConsoleApplication1.Man") // This filter can be added
select new { m, m.NbLinesOfCode }
Notice we put a filter clause, because in the real world pretty much every method calls object.ToString() (this is a particular case).
Now to handle indirect calls this is more tricky. We need to call the magic FillIterative() extension methods on generic sequences.
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
let recursiveCallers = baseMethods.FillIterative(methods => methods.SelectMany(m => m.MethodsCallingMe))
from pair in recursiveCallers
let method = pair.CodeElement
let depth = pair.Value
where method.IsUsing("ConsoleApplication1.Man") // Still same filter
select new { method , depth }
Et voilĂ !

How can I address a script I don't know the type of?

My game uses a variety of different game modes, and I'd like to spawn a different GameController script at the beginning of the scene depending on the game mode selected. Then other items (e.g., Enemies), would reference the main GameController, whether that be GameController_Mode1, GameController_Mode2, etc. But how can I have other objects referencing this if I don't know the type?
Unity iOS requires strict unityscript typing, so I can't use duck typing to get around this.
You can do this the same way you'd do it in C#, polymorphism. Derive all of your controllers from a single base Controller class. Then your GameController var can be set to any instantiation of a derived controller (see Start() in the example below).
Here is a quick example using a simple controller:
#pragma strict
var controller : MyController;
class MyController {
var data : int;
public function MyController(){
this.data = 42;
}
public function Print(){
Debug.Log("Controller: " + this.data);
}
}
class MyController1 extends MyController {
public function MyController1(){
this.data = 43;
}
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
class MyController2 extends MyController {
public function MyController2(){
this.data = 44;
}
public function Print(){
Debug.Log("Controller2: " + this.data);
}
}
function Start () {
controller = new MyController();
controller.Print(); // prints Controller: 42
controller = new MyController1();
controller.Print(); // prints Controller1: 43
controller = new MyController2();
controller.Print(); // prints Controller2: 44
}
I'm making any assumption that your gamecontrollers share function names and that the only difference is the code in each function.
[Update]
Regarding Heisenbug's comment below: You can use GetComponent to get the base class controller if your controller is a component.
Baseclass(BaseController.js):
class BaseController extends MonoBehaviour{
public function Print(){
Debug.Log("BaseController");
}
}
Extended class(Controller1.js):
class Controller1 extends BaseController {
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
Test:
var controller : BaseController;
controller = gameObject.GetComponent("BaseController"); //.GetComponent(BaseController) also works
controller.Print(); // will print "Controller1" if actual attached component is a Controller1 type
While it looks like there are some good answers already but it is worth mentioning Unity's SendMessage system. It is a really simple approach if all you need to do is call functions on the other object SendMessage.
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html
In short you can use the following syntax:
TargetGameObject.SendMessage("targetFunction", argument, SendMessageOptions.DontRequireReceiver);
You can also use SendMessage to call javascript functions from C# scripts or vice versa.

Creating an object passing a lambda expression to the constructor

I have an object with a number of properties.
I want to be able to assign some of these properties when I call the constructor.
The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.
So I thought, wouldn't it be nice if I could say..
MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);
The problem is, I'm too dim to work out how to do it.
Do you know?
C# 3 allows you to do this with its object initializer syntax.
Here is an example:
using System;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar" };
}
}
class Foo
{
public String Bar { get; set; }
}
The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.
Basically the compiler translates the Main method above to something like this:
static void Main()
{
// Create an instance of "Foo".
Foo <>g__initLocal0 = new Foo();
// Set the property.
<>g__initLocal0.Bar = "bar";
// Now create my "Foo" instance and set it
// equal to the compiler's instance which
// has the property set.
Foo foo = <>g__initLocal0;
}
The object initializer syntax is the easiest to use and requires no extra code for the constructor.
However, if you need to do something more complex, like call methods, you could have a constructor that takes an Action param to perform the population of the object.
public class MyClass
{
public MyClass(Action<MyClass> populator)
{
populator.Invoke(this);
}
public int MyInt { get; set; }
public void DoSomething()
{
Console.WriteLine(this.MyInt);
}
}
Now you can use it like so.
var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:
MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};
You can set any of the properties / fields that way./
class MyObject
{
public MyObject(params Action<MyObject>[]inputs)
{
foreach(Action<MyObject> input in inputs)
{
input(this);
}
}
}
I may have the function generic style wrong, but I think this is sort of what you're describing.

Question about var type

I am new to C# 3.0 var type. Here I have a question about this type. Take the following simple codes in a library as example:
public class MyClass {
public var Fn(var inValue)
{
if ( inValue < 0 )
{
return 1.0;
}
else
{
return inValue;
}
}
}
I think the parameter is an anonymous type. If I pass in a float value, then the Fn should return a float type. If a double value type is passed in, will the Fn return a double type? How about an integer value type as input value?
Actually, I would like to use var type with this function/method to get different return types with various input types dynamically. I am not sure if this usage is correct or not?
You can't use var for return values or parameter types (or fields). You can only use it for local variables.
Eric Lippert has a blog post about why you can't use it for fields. I'm not sure if there's a similar one for return values and parameter types. Parameter types certainly doesn't make much sense - where could the compiler infer the type from? Just what methods you try to call on the parameters? (Actually that's pretty much what F# does, but C# is more conservative.)
Don't forget that var is strictly static typing - it's just a way of getting the compiler to infer the static type for you. It's still just a single type, exactly as if you'd typed the name into the code. (Except of course with anonymous types you can't do that, which is one motivation for the feature.)
EDIT: For more details on var, you can download chapter 8 of C# in Depth for free at Manning's site - this includes the section on var. Obviously I hope you'll then want to buy the book, but there's no pressure :)
EDIT: To address your actual aim, you can very nearly implement all of this with a generic method:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
As shown in the listing, the tricky bit is working out what "1" means for an arbitrary type. You could hard code a set of values, but it's a bit ugly:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
Icky - but it'll work. Then you can write:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
etc
You cannot use var as a return type for a method.