How to (accidentally) write into the global context (namespace) with coffeescript? - namespaces

I accidentally stumbled over the following code that actually modified the global namespace:
I though this is not possible?
The following code writes three variables into the global namespace (try it):
this.my_global1=1
#my_global2=2
f= -> #my_global3=3
f()
If you now replace the above code with this in the cofeescript try page
alert("#{[my_global1,my_global2,my_global3]}")
you will see an alert with
1,2,3
This means the statements above modify the global context!
It took me many hours to figure out what was going wrong with my code, because I thought coffeescript protects me form accidental changes of the global environment!

CoffeeScript can't prevent you from doing this, but JavaScript can. Use strict mode:
do ->
"use strict"
this.$ = 3
In non-strict mode, this defaults to window if it isn't specified when the function is called. In strict mode, this becomes undefined, which will throw an error if you try to assign properties to it:
TypeError: Cannot set property '$' of undefined

Related

Prevent printing of output in octave script without adding semicolons everywhere?

Octave by default prints the result of each assignment, which is quite useful on the terminal and can be quite useful for debugging data evaluation scripts. In order to suppress it,
However, it can also be a major annoyance when working on scripts, forgetting a semicolon, and suddenly having major lags in the GUI due to pages over pages of output for that 10000×10000 matrix.
Is there a way to instead suppress the output by default, and instead only echo of assignments, if an explicit trailing , is supplied?
Yes, octave provides silent_functions.
It is false (i.e. 0) by default.
You can set it to 1 to make functions silent, i.e. any evaluations that do not have a semicolon inside the function will not be printed.
Note however, that what you describe, i.e. terminating with a comma, will not display output either when this is enabled. To display output intentionally from a function with this enabled, you will have to use the disp command.
From the docs:
-- silent_functions (NEW_VAL, "local")
Query or set the internal variable that controls whether internal
output from a function is suppressed.
If this option is disabled, Octave will display the results
produced by evaluating expressions within a function body that are
not terminated with a semicolon.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it
calls. The original variable value is restored when exiting the
function.
PS. Note: this also works for scripts, but not for the main console window. Anything you don't terminate with a semicolon in the live console will be printed, regardless of this setting.

Reference to "this" changed inside Sortables Class

I was testing Jakobs patch on the Sortables Class and this line this.reset() gave me a Uncaught TypeError: undefined is not a function.
I don't understand why since the Class has a method reset.
So my solution was to a var self = this; inside the same end: method (here), and called self.reset(); in the same line as I had this.reset(); before. Worked good. Why?
Then just to check (I suspected already) I did a console.log(this == self) and gave false.
Why does using self work but not this?
Fiddle
In javascript the this keyword change accordingly with the execution context
in global code this refer to the global object
inside eval the scope is the same as the calling context one, if no context provided then is the same as above
in all the case below if the this argument passed to .bind .call or .apply is not an object (or null) this will be the global object
when using a function which has been binded to a specific object using .bind then this refers to the this argument passed to bind, the function is now permabinded.
when running a function the context is provided from the caller, if before the function call operator () there is a dot(.) or a [] operator then this refers to the part on the left of such operator, unless the function is permabinded to something else or we are using .call or .apply if so this refers to the this argument unless the function was previously permabinded;
if before the function call operator () there neither the . nor the [] operators then this will refer to the global object (unless the function stores the result of the .bind function)
when running a constructor function (basically when using new) this refers to the object we are creating
now when using the use strict directive things changes a bit, mostly instead of the global object when the context is not given this will be null, but not in all the cases.
I rarely use "use strict" so I just suggest to try it by yourself when in need.
now, what happens when a function is cached inside a variable like this:
var cache = 'A.foo'
if that you lose the context in which the original function was stored, so in this case foo will not be anymore a property on the instance A and when you run it using
cache()
the context will be evaluated using the rules I wrote above in this case the this will refer to the global object.
The semantics of "this" in Javascript are not what is expected by OO programmers. The symbol "this" refers to the dynamic/runtime calling context, not the lexicographic context. For example, if you have an object A with "method" and then do B.method = A.method; B.method(); then the context is now B and that is what this will point to. The difference becomes very apparent in "handler" type situations where the calling context is usually the object with the handler installed.
Your solution using self is sound.
kentaromiura's answer is absolutely right.
That said, mootools provides function.bind() as a way to decide what this will refer inside of your function. this means that if you simply do this :
var destroy = function () {
`bind() [...]
this.reset();
}.bind(this);
it will work as you intended (that is, this will be the same inside of destroy() and outside).
Now, a lot of coders will balk at fiddling with the context, with good reason as it is very difficult to read and maintain. But here you have it and I think bind() is a very nifty trick of mootools.

What are the ramifications of duplicate variable definitions?

I have code that looks like this:
var variableX:uint = something;
if (variableX > 1)
{
var variableY:uint = foo;
}
else
{
var variableY:uint = bar;
}
When compiled in FlashDevelop, the compiler gives the following warning:
Warning: Duplicate variable definition.
Being a beginner with AS3 and programming I don't like compiler warnings. The compiler is looking at me through squinted eyes and saying "Ok, buddy, I'll let you off this time. But I'm warning you!" and then doesn't tell me what's so wrong about what I'm doing.
What should I be aware of when I do something like this? I mean I could obviously define the variable outside of if and then this wouldn't be a problem, but maybe there's something more to this? Or is the compiler just giving a helpful nudge saying "hey, you might have accidentally created two different variables with the same name" ?
You're correct in your assessment of the warning. It's just letting you know there was already a variable in scope with that name and that you're about to redefine it. This way you don't accidentally overwrite a variable. Although they may not appear to be in the same scope if you check out variable hoisting on this page you'll see what the deal is: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9d.html
An interesting implication of the lack of block-level scope is that
you can read or write to a variable before it is declared, as long as
it is declared before the function ends. This is because of a
technique called hoisting , which means that the compiler moves all
variable declarations to the top of the function. For example, the
following code compiles even though the initial trace() function for
the num variable happens before the num variable is declared:
My personal tendency is to just bring the definition up top myself to avoid having extra warnings that make me miss more important issues. Been out of AS3 for a while but in large projects people let things go and you end up with 100s-1000s of warnings and relevant ones get buried.

Is there a way to avoid using 'call' in Coffeescript?

I'm writing a simple Twitter client to play with coffeescript. I have an object literal with some functions that call each other via callbacks.
somebject =
foo: 'bar'
authenticateAndGetTweets: ->
console.log "Authorizing using oauth"
oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
oauth.authorize( this.afterLogin.call this )
afterLogin: ->
this.getTweets(this.pollinterval)
This code works perfectly. Edit: actually this.afterlogin should be sent as a callback above, not ran immediately, as Trevor noted below.
If, within authenticateAndGetTweets, I removed the 'call' and just ran:
oauth.authorize( this.afterLogin )
and don't use 'call', I get the following error:
Uncaught TypeError: Object [object DOMWindow] has no method 'getTweets
Which makes sense, since 'this' in afterLogin is bound to the thing that initiated the callback rather than 'someobject' my object literal.
I was wondering if there's some magic in Coffeescript I could be doing instead of 'call'. Initially I thought using the '=>' but the code will give the same error as above if '=>' is used.
So is there a way I can avoid using call? Or does coffeescript not obviate the need for it? What made '=>' not work how I expected it to?
Thanks. I'm really enjoying coffeescript so far and want to make sure I'm doing things 'the right way'.
As matyr points out in his comments, the line
oauth.authorize( this.afterLogin.call this )
doesn't cause this.afterLogin to be called as a callback by oauth.authorize; instead, it's equivalent to
oauth.authorize this.afterLogin()
Assuming that you want this.afterLogin to used as a callback by oauth.authorize, megakorre's answer gives a correct CoffeeScript idiom. An alternative approach supported by many modern JS environments, as matyr points out, would be to write
oauth.authorize( this.afterLogin.bind this )
There's no CoffeeScript shorthand for this, partly because Function::bind isn't supported by all major browsers. You could also use the bind function from a library like Underscore.js:
oauth.authorize( _.bind this.afterLogin, this )
Finally, if you were to define someobject as a class instead, you could use => to define afterLogin such that it's always bound to the instance, e.g.
class SomeClass
foo: 'bar'
authenticateAndGetTweets: ->
console.log "Authorizing using oauth"
oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
oauth.authorize(this.afterLogin)
afterLogin: =>
this.getTweets(this.pollinterval)
someobject = new SomeClass
you can put a lambda in the function call like so
auth.authorize(=> #afterLogin())
You have to use either the call or apply methods because they set the scope of the function (the value of this). The error results because the default scope is the window object.

Accessing the Body of a Function with Lua

I'm going back to the basics here but in Lua, you can define a table like so:
myTable = {}
myTable [1] = 12
Printing the table reference itself brings back a pointer to it. To access its elements you need to specify an index (i.e. exactly like you would an array)
print(myTable ) --prints pointer
print(myTable[1]) --prints 12
Now functions are a different story. You can define and print a function like so:
myFunc = function() local x = 14 end --Defined function
print(myFunc) --Printed pointer to function
Is there a way to access the body of a defined function. I am trying to put together a small code visualizer and would like to 'seed' a given function with special functions/variables to allow a visualizer to 'hook' itself into the code, I would need to be able to redefine the function either from a variable or a string.
There is no way to get access to body source code of given function in plain Lua. Source code is thrown away after compilation to byte-code.
Note BTW that function may be defined in run-time with loadstring-like facility.
Partial solutions are possible — depending on what you actually want to achieve.
You may get source code position from the debug library — if debug library is enabled and debug symbols are not stripped from the bytecode. After that you may load actual source file and extract code from there.
You may decorate functions you're interested in manually with required metadata. Note that functions in Lua are valid table keys, so you may create a function-to-metadata table. You would want to make this table weak-keyed, so it would not prevent functions from being collected by GC.
If you would need a solution for analyzing Lua code, take a look at Metalua.
Check out Lua Introspective Facilities in the debugging library.
The main introspective function in the
debug library is the debug.getinfo
function. Its first parameter may be a
function or a stack level. When you
call debug.getinfo(foo) for some
function foo, you get a table with
some data about that function. The
table may have the following fields:
The field you would want is func I think.
Using the debug library is your only bet. Using that, you can get either the string (if the function is defined in a chunk that was loaded with 'loadstring') or the name of the file in which the function was defined; together with the line-numbers at which the function definition starts and ends. See the documentation.
Here at my current job we have patched Lua so that it even gives you the column numbers for the start and end of the function, so you can get the function source using that. The patch is not very difficult to reproduce, but I don't think I'll be allowed to post it here :-(
You could accomplish this by creating an environment for each function (see setfenv) and using global (versus local) variables. Variables created in the function would then appear in the environment table after the function is executed.
env = {}
myFunc = function() x = 14 end
setfenv(myFunc, env)
myFunc()
print(myFunc) -- prints pointer
print(env.x) -- prints 14
Alternatively, you could make use of the Debug Library:
> myFunc = function() local x = 14 ; debug.debug() end
> myFunc()
> lua_debug> _, x = debug.getlocal(3, 1)
> lua_debug> print(x) -- prints 14
It would probably be more useful to you to retrieve the local variables with a hook function instead of explicitly entering debug mode (i.e. adding the debug.debug() call)
There is also a Debug Interface in the Lua C API.