JoeStrout/miniscript

self is undefined when calling instance function by address

Closed this issue · 2 comments

Foo={}
Foo.name=null

Foo.getname=function()
    return self.name
end function

foo = new Foo
foo.name = "FooName"

func = @foo.getname
print(func) // Expected: "FooName". Actual: Runtime Error: Undefined Identifier: 'self' is unknown in this context [line 5]

I'm trying to call a function by reference on a foo instance.
Use case: a menu item stores a handler (object instance method) that is invoked when the item is activated.
This worked in one of the previous versions of MiniScript, but now it doesn't. If this is expected behaviour now, is there an alternative way to dynamically (@) call any function on a foo object, so that self is assigned correctly?

If you write your function definition so it have first argument named self, then you can call it both ways:

myFunc = function(self, arg)
// Do something 
end function 
foo = {}
foo.myFunc = @myFunc

// Call 1
foo.myFunc 123

// Call 2
myFunc foo, 123

Yes, this behavior is expected. The standard idiom for something like this is to wrap your instance method in a non-instance method, for example:

handler = function; return foo.getname; end function
handler   // returns "FooName"

Note that this works even when foo is a local variable, as the wrapper captures the local variables where it is defined.