<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">

    <title type="text">Studio Koi Blog</title>
    <subtitle type="text">Studio Koi Blog:</subtitle>
    <link rel="alternate" type="text/html" href="http://studiokoi.com/blog/" />
    <link rel="self" type="application/atom+xml" href="http://studiokoi.com/code/atom" />
    <updated>2011-10-15T22:32:47Z</updated>
    <rights>Copyright (c) 2011, Greg Ferrell</rights>
    <generator uri="http://www.expressionengine.com/" version="2.4.0">ExpressionEngine</generator>
    <id>tag:studiokoi.com,2011:10:16</id>


    <entry>
      <title>Setting Gnome 3 as the default desktop in Ubuntu 11.10</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/setting_gnome_3_as_the_default_desktop_in_ubuntu_11.10" />
      <id>tag:studiokoi.com,2011:blog/1.76</id>
      <published>2011-10-16T01:56:19Z</published>
      <updated>2011-10-15T22:32:47Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>So, like most people who get excited about new software, I installed the Ubuntu 11.10, Oneiric Ocelot update as soon as it was available this week. I have said it loudly on <a href="http://twitter.com/gregferrell/">twitter</a> before, but I really dislike Ubuntu Unity. The sad thing is that 11.10 not only comes with Unity as default, it uninstalls Gnome classic on upgrade, so if you were using classic in 11.04 like I was: Rude awakening.</p>

<p>Fortunately, there are some steps you can take to install Gnome 3 and make it the default booting shell for Ubuntu 11.10. First, you will need to install the Gnome shell in the terminal or through the software sources app. (I prefer to install from the terminal as it gives better information if an install fails.)</p>

<p><pre class="brush: bash">sudo apt-get install gnome-shell</pre></p>

<p>You might be tempted to install GDM instead of using LightDM for the initial login screen. I had trouble doing this and the system absolutely does not like having GDM and LightDM installed at the same time (for obvious reasons). But to get past that, I edited the LightDM conf to always boot into Gnome and went into System Settings > User Accounts and set my user account to auto login. This way i only have to see the LightDM screen or Unity if i specifically log out to that screen. Thankfully, someone on <a href="http://askubuntu.com/questions/62833/how-do-i-change-the-default-session-for-lightdm-when-using-auto-logins"> AskUbuntu had the right answer for setting the default shell in LightDM</a>.</p>

<p>Once you&#8217;ve installed Gnome, go to the terminal and sudo edit the LightDM conf file (I prefer to use gedit):</p>

<p><pre class="brush: bash">sudo gedit /etc/lightdm/lightdm.conf</pre></p>

<p>Then edit the line that says:</p>

<p><pre class="brush: bash">user-session=ubuntu</pre></p>

<p>to</p>

<p><pre class="brush: bash">user-session=gnome-shell</pre></p>

<p>Now reboot. This will have you happily booting into Gnome 3 without a login prompt or the ugly ass LightDM screen. On another note, if you don&#8217;t want to see that screen when you want to invoke the reboot command (as its not possible from inside Gnome or Unity, you have to log out), from the terminal, type:</p>

<p><pre class="brush: bash">sudo reboot</pre></p>

<p>Some other good resources for pimping out your Ubuntu 11.10 Gnome3 install:</p>

<p><a href="http://www.webupd8.org/2011/10/things-to-tweak-after-installing-ubuntu.html">Things to tweak after installing Ubuntu 11.10 Oneiric Ocelot</a></p>

<p><a href='http://www.webupd8.org/2011/10/official-gnome-shell-extensions.html'>Official Gnome Shell Extensions</a></p>


      ]]></content>
    </entry>

    <entry>
      <title>Ascension Gets an iOS version and it&#8217;s really really good</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/ascension_gets_an_ios_version_and_its_really_really_good" />
      <id>tag:studiokoi.com,2011:blog/1.71</id>
      <published>2011-08-12T14:18:32Z</published>
      <updated>2011-08-12T10:53:44Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>Last weekend I went with some friends to <a href="http://www.gencon.com/">GenCon Indy</a>. It was a blast and we got to try out some new board glare that we&#8217;ve had our eyes on.</p>

<p>My friend Dave picked up a couple of pre-release games like <a href="http://wizkidsgames.com/quarriors/">Quarriors</a> (amazing dice deck building game), and some dominion expansions. One of the games we demoed was <a href="http://www.ascensiongame.com/">Ascension</a>. Ascension is a deck building game like <a href="http://boardgamegeek.com/boardgame/36218/dominion">Dominion</a>, but instead of piles of cards, only a few are out at a time and get replaced when purchased or defeated. I wasn&#8217;t blown away with it, but it was a cool idea. I just liked Quarriors better and we went home with it.</p>

<p>Fast forward to this week where Dave tells me that there is an <a href="http://itunes.apple.com/us/app/ascension-chronicle-godslayer/id441838733?mt=8&amp;ign-mpt=uo%3D4">iOS version of Ascension</a>, and not only is it pretty good, it&#8217;s for both iPad and iPhone. I hate it when you have to purchase an app for each device instead of it being universal, so that&#8217;s a huge bonus for me.</p>

<p>Normally I dont write about games, but what really intrigues me about it is how seamless of a transition it is from the board game to the handheld as far as understanding of play. Literally, since i knew how to play the board game, the only part of the tutorial for the iOS game i needed was the flyouts for the cards. However, if you don&#8217;t know how to play the game, the built in tutorial is rather good.</p>

<p>I have yet to find a bug and thats just nutty for such potential complication as translating a board game with specials rules to a handheld device. (Granted, many more complicated games like RPGs, etc are coded on devices, but they are created with the intent of the device in the first place.) It&#8217;s just a really well done game.</p>

<p>There is a video of the game on iPad from Gen Con, with an upcoming expansion that ill be available through in app purchasing, but i&#8217;ve also included some screenshots.</p>

<iframe width="560" height="349" src="http://www.youtube.com/embed/aWuooUDceYE" frameborder="0" allowfullscreen></iframe>

<p>Opening Screen:</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_01.jpg" alt="Ascension iOS: Opening Screen" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>Choose character and CPU opponent or other players for pass and play!</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_02.jpg" alt="Ascension iOS: Choose character and CPU opponent or other players for pass and play" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>Have multiple games going in case you want to stop a personal game and play a new one with friends (also has online play):</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_03.jpg" alt="Ascension iOS: Have multiple games going" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>Zoom in on cards to see what they do and use them while zoomed. (Very intuitive.):</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_04.jpg" alt="Ascension iOS: Zoom in on cards" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>View opponents hand:</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_05.jpg" alt="Ascension iOS: View opponents hand" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>View opponents previous play log:</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_06.jpg" alt="Ascension iOS:View opponents previous play log" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>View discard pile:</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_07.jpg" alt="Ascension iOS: View discard pile" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>End game view showing all cards for each player and how the score was obtained:</p>

<p><img src="http://studiokoi.com/images/uploads/ascension/ascension_08.jpg" alt="Ascension iOS: End game view" style="border: 0;" width="600" height="400" alt="image" /></p>

<p>This is just a really well put together game and how mobile games should be.</p>
      ]]></content>
    </entry>

    <entry>
      <title>Automator: Add &#8216;right click, open with&#8217; to folders in Finder</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/automator_add_right_click_open_with_to_folders_in_finder" />
      <id>tag:studiokoi.com,2011:blog/1.69</id>
      <published>2011-06-19T03:35:35Z</published>
      <updated>2011-06-24T02:28:36Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>I use OS X and Ubuntu on a daily basis with my dev machines. One of the things that I like that Ubuntu can do is open folders with applications on right click. Unfortunately, OS X doesn&#8217;t do this by default, but we can accomplish it easily with an Automator Workflow. (It would be nice if  <a href="http://www.binaryage.com/" title="Mac applications and development tools from BinaryAge" >Binary Age</a> would add this feature to TotalFinder  <img src="wink.gif" width="19" height="19" alt="wink" style="border:0;" /> ) .</p>

<p>One of the options in OS X&#8217;s Automator workflow outputs is &#8216;Service&#8217;, which will allow us to put a finished workflow into a right click menu for files and folders.</p>

<p>First, launch Automator and choose &#8216;Service&#8217;:</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_1.png" alt="Automator: choose Services" style="border: 0;" alt="image" /></p>

<p>Now, the first item shown is an automatic file list receiver from Finder. Because we need to select the app we want to open the files with, we need to store this as a variable. The first thing we need is &#8216;Set Value of Variable&#8217; from the Utilities heading. This will allow us to store the files into a variable so we can use it later. Drag the &#8216;Set Value of Variable into the workflow and double click the variable dropdown and make a new variable named &#8216;files&#8217;.</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_2.png" alt="Set Value of Variable" style="border: 0;" alt="image" /></p>

<p>The next thing we need is &#8216;Ask for Finder Items&#8217; under Files &amp; Folders. This will allow us to prompt for the application we are going to open the selected files with. (If you can restrict it to file extensions, i am not sure how, so for now, I just set it to type &#8216;file&#8217;.) Change the Prompt to &#8216;Choose an Application&#8217; and set the starting folder to your Applications folder. Then, right click the action window and select &#8216;Ignore Input&#8217; so we don&#8217;t receive any of the files from the previous action in the workflow:</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_3.png" alt="Ask for Finder Items" style="border: 0;" alt="image" /></p>

<p>Now we need to capture this as a variable, so from the Utilities folder, find &#8216;Set Value of Variable&#8217; and drag it into your workflow. It should automatically pin itself to the previous item. Name the variable &#8216;selectedapp&#8217; by double clicking the &#8216;New Variable&#8217; dropdown box.</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_4.png" alt="Set value of Variable" style="border: 0;" alt="image" /></p>

<p>We have our chosen app, and we need to retrive the value of the selected Finder items so we can feed them to the app to open them. From the Utilities folder, select &#8216;Get Value of Variable&#8217; and drag it into the workflow. From the variable list at the bottom, drag the &#8216;files&#8217; variable into the variable dropdown. Then, right click the action window and select &#8216;Ignore Input&#8217; so we don&#8217;t receive any of the files from the previous action in the workflow:</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_5.png" alt="Get Value Of Variable" style="border: 0;" alt="image" /></p>

<p>The last item we need is an Application opener to open the selected Finder items with the previously prompted for application. Under &#8216;Files &amp; Folders&#8217;, select &#8216;Open Finder Items&#8217; and add it to the workflow. Then, from the variable list at the bottom of the window, drag in the &#8216;selectedapp&#8217; variable we created before onto the &#8216;Open Finder Items&#8217; item in the workflow. It should automatically change the &#8216;Open with:&#8217; value to the variable.</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_6.png" alt="Open Finder Items With" style="border: 0;" alt="image" /></p>

<p>Your completed workflow should look like this:</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_7.png" alt="Completed workflow" style="border: 0;" alt="image" /></p>

<p>Now safe the file (It should automatically be saving as a finder service) and name it &#8216;Open Files With&#8230;&#8217;. Use the workflow by highlighting the folder you want to open, right click and go to the services menu and select &#8216;Open Files With&#8230;&#8217;.</p>

<p><img src="http://studiokoi.com/images/uploads/automator_screen_8.jpg" alt="Finished Product" width="627" height="485" style="border: 0;" alt="image" /></p>

<p>If you use some applications more than others, then an option to create a directly opening right click workflow is to remove the middle two steps for selecting an application, and for the last step, use a selected application instead of the &#8216;selectedapp&#8217; variable. </p>

<p>Enjoy!&nbsp; <img src="grin.gif" width="19" height="19" alt="grin" style="border:0;" /></p>
      ]]></content>
    </entry>

    <entry>
      <title>Promote JS ExpressionEngine plugin</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/promote_js_expressionengine_plugin" />
      <id>tag:studiokoi.com,2011:blog/1.68</id>
      <published>2011-04-25T14:53:24Z</published>
      <updated>2011-05-02T21:19:25Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>Have you been promoting JavaScript? Did you even know that you could/should be? It just got easier to help if you are using ExpressionEngine.</p>

<p>At <a href="http://jsconf.us" tile="JSConf: JavaScript Conference">JSConf 2010</a>, <a href="http://twitter.com/voodootikigod">Chris Williams</a> started a project called <a href="http://promotejs.com/">PromoteJS</a> to help get bad JavaScript references off the web. You will know how important a cause this is if you have ever done a Google search for JavaScript documentation or help. The top results are deplorable. (NEVER use w3schools.)</p>

<p>The aim of PromoteJS is to use a banner with keywords relating to JavaScript to help the SEO of better documentation. There is even a site named <a href="http://arewefirstyet.com">Are We First Yet?</a> to help us see when better docs are at the top.</p>

<p>It&#8217;s easy to help. You can go to the PromoteJS website and copy the code for a banner there for your website, or you can use the Wordpress plugin located there.</p>

<p>For ExpressionEngine users, I have made a plugin that works on EE 1.x and 2.x and you can download it <a href="https://github.com/gregferrell/ee_promotejs">here</a>.</p>
      ]]></content>
    </entry>

    <entry>
      <title>Converting numbers to letters quickly in PHP</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/converting_numbers_to_letters_quickly_in_php" />
      <id>tag:studiokoi.com,2011:blog/1.67</id>
      <published>2011-02-27T18:22:03Z</published>
      <updated>2011-02-27T13:27:04Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>For a personal project, I needed to convert numbers to letters and double letters when greater than 26. This is rather a simple thing in PHP using the <a href="http://us.php.net/manual/en/function.chr.php" title="PHP manual: chr()">chr function</a>.</p>

<p>The short of it is that you divide by 26 and get the letter, then repeat the letter for every multiple of 26. This gives us our double letters accurately. I also added an option for uppercase.</p>

<script src="https://gist.github.com/846335.js?file=num_to_letter.php"></script>
      ]]></content>
    </entry>

    <entry>
      <title>Quickly unserialize PHP serialized object data from the command line</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/quickly_unserialize_php_serialized_object_data_from_the_command_line" />
      <id>tag:studiokoi.com,2010:blog/1.62</id>
      <published>2010-12-19T21:53:38Z</published>
      <updated>2010-12-19T16:56:40Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <content type="html"><![CDATA[
        <p>I do a lot of testing with PHP that requires serialized data to be passed and retrieved. Many times this can be a pain to read, so i made a quick shell script that will take a normal input or if thats missing, get the clipboard from OS X and serialize it. This requires that you have the PHP CLI installed (default on OS X).</p>

<p> Then quite handily, you can just type <code>php_unserialize</code> in your terminal and it will spit out a var_dump of the unserialized data that you can read.</p>

<script src="https://gist.github.com/747642.js?file=php_unserialize.sh"></script>
      ]]></content>
    </entry>

    <entry>
      <title>The Cobbler&#8217;s assistant&#8217;s children have no shoes, either</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/the_cobblers_assistants_children_have_no_shoes_either" />
      <id>tag:studiokoi.com,2010:blog/1.56</id>
      <published>2010-08-17T23:48:10Z</published>
      <updated>2010-08-18T12:49:11Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="News"
        scheme="http://studiokoi.com/code/category/News"
        label="News" />
      <content type="html"><![CDATA[
        <p>Last week we released a new design for <a href="http://solspace.com">Solspace</a>. Everything went over pretty well, aside from some small hiccups. Not bad for a new site design launch. I am quite proud that we have a new face as we are very dedicated to our work and our old website just didn&#8217;t reflect that. Good change.</p>

<p>Like the <a href="http://www.solspace.com/blog/entry/cobblers_children_have_no_shoes/" title="Solspace - Cobblers’ Children Have No Shoes"> blog post about the redesign</a> suggests, it is hard to work on your on self image when you are spending all of your time trying to make sure everything else is taken care of. Customer service, bug fixes, and fresh products are first and foremost, because that&#8217;s what&#8217;s most useful to customers. However, a good face is very important.</p>

<p>This sort of brings me to this website. I added a new design recently, but didn&#8217;t spend much time on it, as i don&#8217;t usually have much to give because I am trying to make my work at Solspace the best it can be. It really needed the update, though because it was just slow and hard to read. However, it&#8217;s still not to my liking and will probably redesign again in the coming months and start to chronicle a bit more of what i am working on now.</p>

<p>I still want to share knowledge and pay forward the help so many others have given me over time.&nbsp; <img src="wink.gif" width="19" height="19" alt="wink" style="border:0;" /></p>
      ]]></content>
    </entry>

    <entry>
      <title>Ghetto tag limiting in EE 2</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/ghetto_tag_limiting_in_ee_2" />
      <id>tag:studiokoi.com,2010:blog/1.54</id>
      <published>2010-05-16T00:33:39Z</published>
      <updated>2010-05-21T20:07:41Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="ExpressionEngine"
        scheme="http://studiokoi.com/code/category/ExpressionEngine"
        label="ExpressionEngine" />
      <content type="html"><![CDATA[
        <p>So, I finally decided to take the time to update my website to the ExpressionEngine 2.0 Beta.</p>

<p>This means that some of my stuff is going to be broken, but I can live with that. Going to improve how things are done and use better components this way. But the transition had a couple of small hiccups&#8230;</p>

<p>Step one, however, is that I use a tag limiter on the front page because I am too lazy to copy paste paragraphs into the summary field. Besides, i shouldn&#8217;t have to. This is a CMS right? I should only have to work once. Well, the tag limiter i was using was broken, so instead of working too hard, I made this ghetto tag limiter with in template php.</p>

<pre class="brush: php">
&#36;content = &lt;&lt;&lt; END_OF_CONTENT
{body}

END_OF_CONTENT;
	
&#36;content_array = explode('&lt;/p&gt;', &#36;content);

echo &#36;content_array[0] . '&lt;/p&gt;' . &#36;content_array[1] . '&lt;/p&gt;';
</pre>

<p>Pretty simple, and as you can see, quite effective. Though, I will have to make this into an addon for later. That is my job now <img src="smile.gif" width="19" height="19" alt="smile" style="border:0;" />.</p>
      ]]></content>
    </entry>

    <entry>
      <title>Simple argument defaults in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/simple_argument_defaults_in_javascript" />
      <id>tag:studiokoi.com,2009:blog/1.52</id>
      <published>2009-09-27T03:51:50Z</published>
      <updated>2010-05-21T20:37:51Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>In many other interpreted programming languages like: Python, PHP, ActionScript 3.0, etc., you can have defaults to arguments that do not get passed to functions. In the three a fore mentioned languages, it's as easy as saying arg = 'default' inline in the function definition. This however is not available in the JavaScript interpreter. (It might be in ECMAScript 5, though.) But that can easily be remedied with a simple helper function.</p>

<p>I have met other programmers that find it ridiculous that you have to create features in JavaScript that are built into other languages. They use that to put down JavaScript and call it a terrible language. However, I think that's part of what makes JavaScript so great. JavaScript, though not as powerful in features as some other languages, offers enough flexibility and expressiveness that you can create what you feel that you are missing. Lets take a look at the problem and see how easy we can remedy it.</p>

<p>First, look at a basic function that is about the same in most C based languages:</p>

<pre class="brush: js">
function foo(arg1, arg2)
{
	return arg2;
}
foo('one', 'two'); 	// returns 'two'
foo('one'); 		// undefined
</pre>

<p>In the above example, you MUST have a second argument passed to the function, or you get an error. Some people remedy that like so:</p>

<pre class="brush: js">
function foo(arg1, arg2)
{
	//check for defaults
	var arg1 = arg1 || "one";
	var arg2 = arg2 || "two";
	
	return arg2;
}
foo('one', 'also two');	// returns 'also two'
foo('one'); 		// returns 'two'
</pre>

<p>The above works OK, but is a little cumbersome. The logical or operator or '||' (double pipe) in JavaScript returns the first item if it is truthy, or the second item no matter what. Usually, you'll only see that in if statement blocks, but this idiom works well as an either or return value and is used such. <strong>NOTE: This idiom would not work well with any value passed that is falsey: A blank string, an integer 0, boolean false, etc., because it returns the second item when the first argument is a falsey value and not just undefined or null.</strong></p>

<p>The above fix is lousy, though, because it becomes a mess when you have more than one optional argument. Take the following example that uses an object literal as the only argument and allows for passing only the arguments you want to send:</p>

<pre class="brush: js">
function foo(args)
{
	//check for defaults
	args.arg1 = args.arg1 || "one";
	args.arg2 = args.arg2 || "two";
	args.arg3 = args.arg3 || "three";
	
	return args.arg2;
}
foo({"arg2":"also two"});	// returns 'also two'
foo({"arg1":"also one"});	// returns 'two'
</pre>

<p>The above works a little better because it allows you to pass only the arguments you want without having to null out others. It still presents ugly default checking and the same issues with falsey statements. We can use the same idea, but implement it far better with a simple function that will take a set of defaults and replace passed items over it and return the a useable object with all defaults and arguments in one.</p>

<pre class="brush: js">
function defaults(def, arg)
{
	for(var i in arg)
	{
		def<i> = arg<i>;
	}
	return def;
}
</pre>

<p>The above code takes exactly two arguments, the first being an object with the default 'name:value' pairs for your arguments. The second one is the argument object actually passed to the defaults function. The second object is iterated over and all of its values are placed over the default ones and the default object is returned. This will give a usable object with defaults in place and actual passed arguments where presented.</p>

<p>How it actually works can be displayed as such:</p>

<table class="inline-table">
	<thead>
		<tr>
			<th>Defaults Object</th>
			<th>Arguments Object</th>
			<th>Resulting Object</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>"one"</td>
			<td>(nothing passed)</td>
			<td>"one"</td>
		</tr>
		<tr>
			<td>"two"</td>
			<td>"also two"</td>
			<td>"also two"</td>
		</tr>	
		<tr>
			<td>"three"</td>
			<td>(nothing passed)</td>
			<td>"three"</td>
		</tr>
	</tbody>
</table>

<p>Lets see it in action:</p>

<pre class="brush: js">
function foo(args)
{
	args = defaults({
		arg1 :"one",
		arg2 :"two",
		arg3 :"three"
	}, args);
	
	return args.arg2;
}
foo({"arg2":"also two"});	// returns 'also two'
foo({"arg1":"also one"});	// returns 'two'
</pre>

<p>The default arguments are much less cluttered and were properly applied to items missing from the passed args object. Armed with our new defaults function and knowledge of how to use a single object to send all arguments, we can now safely send only select arguments, falsey or not, and have default arguments take care of the rest.</p>

<p>Enjoy!</p>
      ]]></content>
    </entry>

    <entry>
      <title>I Won Frank Peak&#8217;s Twitter Contest!</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/i_won_frank_peaks_twitter_contest" />
      <id>tag:studiokoi.com,2009:blog/1.51</id>
      <published>2009-09-09T06:18:06Z</published>
      <updated>2011-07-26T15:47:07Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="News"
        scheme="http://studiokoi.com/code/category/News"
        label="News" />
      <content type="html"><![CDATA[
        <p>If you like art at all and you don't already follow <a href="http://twitter.com/frankpeak" title="Frank Peak on Twitter">Frank Peak</a> on twitter, or visit <a href="http://frankpeak.com" title="Frank Peak's Online Portfolio">his website</a>, I would highly recommend it. He periodically has "Almost Daily Drawings" that are his random doodles and concept drawings. His <a href="http://frankpeak.com/portfolio.html" title="Portfolio - Frank Peak">portfolio</a> is also very, VERY good.</p>

<p>Frank is a very skilled illustrator and 3D artist who recently held a <a href="http://www.frankpeak.com/blog/?p=154" title="BUTTON PACK GIVE AWAY! - Frank Peak">contest</a> on Twitter for people who would retweet him. I was one of the fortunate winners of the contest.</p>

<p>Included in the package was a SWEET envelope that Frank personalized for each winner with random (and rather cute) artwork. Inside the package was a button pack with buttons by <a href="http://royalbuttons.com" title="Royal Buttons -  Custom Buttons Made to Order">Royal Buttons Custom Buttons</a>. There was also an unbent copy of the package art, and a sweet random drawing on nice card stock with a personal note from Frank, thanking the winner for participation.</p>

<p>Frank said he would also have some future contests, so even though this one is over, there could be some stuff up for grabs later.</p>

<div class="thumb-box">
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_1.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_1_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_2.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_2_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_3.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_3_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_4.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_4_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_5.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_5_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_6.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_6_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_7.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_7_t.jpg" /></a>
<div class="clear-left"></div>
</div>

      ]]></content>
    </entry>

    <entry>
      <title>Execution order of functions and variables in JavaScript and ActionScript.</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/execution_order_of_functions_and_variables_in_javascript_and_actionscript" />
      <id>tag:studiokoi.com,2009:blog/1.45</id>
      <published>2009-04-13T07:17:37Z</published>
      <updated>2010-05-19T15:24:39Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>Many newcomers to web development may not be used to how web implementations of JavaScript execute. Namely, in what <em>order</em> it executes. This can be the source of many errors that are difficult to pinpoint if you aren't experienced with it. I think this also affects people who are very experienced with other programming languages and fosters a lot of undeserved hate towards ActionScript and JavaScript. (It's important to note that not all implementations of JavaScript are the same, and that some may in fact defer from what is said below. This article concerns browser and Flash based ECMAScript.)</p>

<p>The thing to understand about JavaScript is that it isn't compiled for the most part. (This is not <em>exactly</em> true for ActionScript because of the introduction of classes in ActionScript 2.0, however, the runtime script remains the same. You might argue that it compiles into a *.swf file, but in reality, that is the combination of everything that has to do with the Flash file. The ActionScript still remains live.) It's good that it isn't compiled though, because this allows for much more dynamic, expressive coding.</p>

<p>So, if it isn't compiled, how does it work? Browser-based JavaScript code is all executed at first calling, nothing is compiled or cached in a scope until it is called (except AS2 &amp; AS3 classes). It works this way because, with the exception of basic, immutable variable types: strings, booleans, numbers, and 'undefined', every variable in JavaScript is an object. This includes 'null' and functions ('null' is technically a basic variable, but is reported as an object in JavaScript). Since functions are objects, this means their value in memory is also like an object and names are only assigned by reference. Lets see how this works:</p>

<pre class="brush: js">
//bob first initialization
function bob()
{
	alert('bob');
}

//set jan to bob via reference
var jan = bob;

//set bob to another function
function bob()
{
	alert('newbob');
}

jan(); //alerts 'bob'
bob(); //alerts 'newbob'
</pre>

<p>This where things can be very confusing to people who are used to other languages where functions are <em>just</em> functions and can only be written once to a variable name at compile time. In order to understand better, let's write the same code again with anonymous functions:</p>

<pre class="brush: js">
//bob first initialization
var bob = function()
{
	alert('bob');
};

//set jan to bob via reference
var jan = bob;

//set bob to another function
bob = function()
{
	alert('newbob');
};

jan(); //alerts 'bob'
bob(); //alerts 'newbob'
</pre>

<p>This is how functions are actually assigned in JavaScript. The traditional C style that was seen in the previous example is translated at runtime into something like the above. So, when you code JavaScript, imagine instead that all functions are really variable pointers to anonymous functions in memory. (ActionScript 3.0 in strict mode attempts to stop this sort of behavior by warning you when your code tries to overwrite variables that have already been set. While this is good for heavier languages, I think it is moving away from what makes ECMAScript really dynamic in the first place.)</p>

<p>At this point, you might be asking: "Why is all this important to the execution order of JavaScript?". This gives you background as to why JavaScript doesn't execute anything until runtime. In light of this, there is one thing JavaScript does to speed things up that is VERY important to understanding its execution order: JavaScript caches declared functions <em>before</em> any other variables, after this, it goes back to the top of the scope and runs variable definitions and functions calls in the order that they appear. This is where the confusion begins for the uninitiated.</p>

<p>Let's say for example that you have a function that returns a value from a passed variable. You might want to assign a variable to the result of that function like so:</p>

<pre class="brush: js">
var newNumber = secondPower(5); //25

//first definition of function
function secondPower(n)
{
	return n * n;
}
</pre>

<p>This works because the function was cached before the variable was assigned. However, doing things this way in your own code is a <strong>TERRIBLE</strong> idea because it can cause more problems than it solves. Lets look at an example of where this might fail. Remember our previous example where we assigned the anonymous function to a variable name? While in that example, it worked perfectly, it actually causes a strange thing to happen to execution order:</p>

<pre class="brush: js">
var newNumber = secondPower(5); //error, secondPower is not defined yet

//some parsers would not even get this far due to the above error
//thrown errors in ECMAScript halt the execution scope they are in
var secondPower = function(n)
{
	return n * n;
};

var newNumber2 = secondPower(5); //25
</pre>

<p>This error happens because when the parser came through, it cached the anonymous function before anything else, but <em>not</em> the variable name assignment to the anonymous function. Therefore, when we called 'secondPower', it had not been assigned yet and the first calling was undefined and possibly threw an error. It is important to remember that the bad thing that happened here was not the fact that we assigned a variable name to an anonymous function in place of the classic C way to declare a function, but rather the bad idiom of calling a function before it is assigned. Anonymous functions offer huge benefits to ECMAScript and are not inherently bad.</p>

<p>Other problems can arise from calling functions before they are declared even if the function is written in the classic style. Perhaps the function we use for variable assignment requires an outside variable to function properly. This would cause an error if the function was called before the assignment of the dependent variable took place:</p>

<pre class="brush: js">
var newNumber = multiplyNumber(5);
//multiple is not defined yet, incorrect result with possible error 

var multiple = 2;

//this is cached and available before all other variables
function multiplyNumber(n)
{
	return n * multiple;
}
</pre>

<p>As we can see here, an error would occur in our variable assignment because even though the function was properly cached, its dependent was not assigned yet and the function could not execute properly.</p>

<p>So, knowing this, what should you do to avoid these errors? Here is a quick list to help you when writing your code:
	<ul>
		<li>Never call a function before it is declared</li>
		<li>Declare all variables in a execution scope as soon as possible</li>
		<li>Only assign variables to a function result after all functions and other variables have been declared</li>
	</ul>
</p>

<p>Just to reiterate, let's look at how a good code setup should be writen:</p>

<pre class="brush: js">
//declare all variables as soon as possible
var newNumber, multiple = 2;

//declare all functions before calling them
function multiplyNumber(n)
{
	return n * multiple;
}

//finally, set variable values that require function results
newNumber = multiplyNumber(5); //10
</pre>

<p>Declaring your variables and functions in this way will allow you to use more expressive methods to set functions and will most importantly avoid errors. For some further reading, check out <a href="http://javascript.crockford.com/code.html" title="Code Conventions for the JavaScript Programming Language">Douglas Crockford's recommendations on JavaScript coding conventions</a>.</p>

<p>While I mostly mentioned JavaScript in this Article, the majority of these principles and Douglas Crockford's suggestions apply to ActionScript as well.</p>
      ]]></content>
    </entry>

    <entry>
      <title>Type&#45;checking arrays in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/typechecking_arrays_in_javascript" />
      <id>tag:studiokoi.com,2009:blog/1.44</id>
      <published>2009-01-10T08:06:00Z</published>
      <updated>2009-01-26T15:43:54Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>In JavaScript the typeof operator reports an array as 'object'. While this is technically correct (an array in JavaScript is really just a specialized object), it's a pain in the neck when you are type checking a variable.</p>

<p>There are a number of ways to identify an array in JavaScript. Checking for properties of an array isn't totally accurate because you can add any named member to an object to imitate an array. Checking for 'instanceof Array' works most of the time but could be tricky in some implementations of JavaScript.</p>

<p>Mark Miller of Google gives us a solution that is standard to the ECMAScript documentation:</p>

<pre class="brush: javascript">Object.prototype.toString.apply(value) === '[object Array]';</pre>

<p>What this essentially does is take the standard Object method "toString" and applies it to the passed argument (which is your array you are checking). This makes sure that it reports itself according to standard, which all real arrays should. We can implement it in an easy checking function that returns a boolean:</p>

<pre class="brush: javascript">function isArray(a)
&#123;
	return Object.prototype.toString.apply(a) === '[object Array]';
&#125;</pre>

<p>Props to Douglas Crockford because I read about this on his blog. There is also some <a href="http://blog.360.yahoo.com/blog-TBPekxc1dLNy5DOloPfzVvFIVOWMB0li?p=916#comments" title="Douglas Crockford | Yahoo 360">further discussion</a> there on using this method and i recommend reading it.</p>

<p>As a bonus of sorts, this also works in ActionScript 2.0 and ActionScript 3.0.</p>
      ]]></content>
    </entry>

    <entry>
      <title>JavaScript Errors: Testing for the existence of functions in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/javascript_errors_testing_for_the_existence_of_functions_in_javascript" />
      <id>tag:studiokoi.com,2008:blog/1.43</id>
      <published>2008-12-29T22:38:21Z</published>
      <updated>2010-05-20T14:57:22Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>When using multiple JavaScript libraries, it is inevitable that one JavaScript file will need to call functions named in other libraries. This is necessary but can cause issues if all of the libraries aren't present.</p>

<p>Error handling with JavaScript is somewhat lackluster. With this in mind, you should do your best to catch and handle errors and avoid sending them to the end-user. In order to prevent errors and allow for scalability, you should test for functions that aren't present in the script where you are calling them.</p>

<p>Lets say for example that you have downloaded a JavaScript library named "bob.js" and it contains just a main function named "bob". To keep things clean, you might load this file separately. (Of course this is a bit unrealistic, no one would make a separate file for one function, but for the sake of example, bear with me.) Your loading code might look like this:</p>


<pre class="brush: xml">&lt;script type="text/javascript" src="bob.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="mycode.js"&gt;&lt;/script&gt;</pre>

<p>So, correctly, we have loaded the "bob" library first and our code second.</p>

<p>For the sake of example and understanding, lets suppose that the "bob" function just returns a simple math result. It isn't important what the bob function does, but it might be easier for some to understand if we had a real example:</p>

<pre class="brush: javascript">//bob.js
function bob(n)
&#123;
	return n * n;
&#125;</pre>

<p>Now this takes us to our real example. Given that we have the function "bob" in another file, we want to use it in our own code, "mycode.js". When the page loads, we want to add a div tag with some text that has a number in it. We are going to use the "bob" function to return the number to the power of 2 and write it:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	var newNum = bob(oldNum);

	//set the body tag to a variable
	var body = document.getElementsByTagName('body')[0];
	
	//make the div container
	var myDiv = document.createElement('div');
	
	//create the text container
	var myText = document.createTextNode(newNum);
	
	//add the text to the div
	myDiv.appendChild(myText);
	
	//add the div to the body
	body.appendChild(myDiv);
&#125;</pre>

<p>While the above code could be written quite a bit smaller, it works well and it is plain what is happening. You run into an issue however when the "bob.js" file isnt present. When you run into an error in JavaScript, it usually kills the chain the function or event is called in. So in the above instance, as soon as it hit the second variable, and the bob code wasn't present, the code would simply halt on error and nothing would display on screen, potentially breaking many other things in the process.</p>

<p>This brings the issue of error handling and function testing. One of the tools that we do have in JavaScript is the try/catch(/finally) statement. It is very handy for areas of code that can be error prone or have outside influence on the application. We could fix our example by adding a try/catch statement that would have a backup variable in case the "bob.js" isn't present:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	try &#123;	
		//works if bob is present
		var newNum = bob(oldNum);
	&#125; catch(e) &#123;
		//catches the error if bob is missing and provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This will effectively remove the chance for error if "bob.js" isn't present. However, the try/catch statement takes a bit of a performance hit due to all it is designed to do. When simply testing for functions, I feel it is a bit verbose.</p>

<p>My personal preference is just to test for the existence of the function before I attempt to call it. This way you don't spend the CPU time calling the function, getting the failure, sending the error, catching the error, then running the error block. When testing for a function, it's usually best to make sure it is actually a function rather than simply checking for it to be not undefined. This is doubly important in situations where you are using multiple libraries or working with a lot of people on the same file. Your code and their code could have the same name for two different types of objects. JavaScript has no overwrite protection even on its own built in functions unless specific platforms add it in, therefor you must take it upon yourself to check.</p>

<p>Checking for the existence of functions can be done easily using the typeof operator in JavaScript. Many times, I code that simply checks for "undefined" or not, then lets the code run. As mentioned above, this still leaves some potential for errors in your code. Granted, there will always be margin for error, but the goal is to make habits that minimize it and help you the real issues. Therefore I think it is better to make sure your function is actually a function. The same code we used with the try/catch statement can be written similarly with the typeof checking:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	if(typeof bob === "function") &#123;	
		//works if bob is present and is a function
		var newNum = bob(oldNum);
	&#125; else &#123;
		//if bob is not present, provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This has better performance than the try/catch statement and gives you a better idea where an error could be if it occurs. However, we could write this even shorter to make the code a little cleaner using a ternary operator:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	//if bob is present and is a function, make number
	//if bob is not present, provides an alternative
	var newNum = (typeof bob === "function")? bob(oldNum) : oldNum;

	//..etc
&#125;</pre>

<p>One last thing to mention when using typeof. It will throw an error if you are testing for a function inside of a nonexistent parent. So, say "bob" is an object, with a subobject "math", with a method called "double". If we test for "bob.math.double" and "bob" doesn't exist, JavaScript will throw an error with the typeof operator. To avoid such errors you could test for each segment of the method's parent chain before testing for the method itself:</p>
<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	if(typeof bob === "object" && 
	   typeof bob.math === "object" &&
	   typeof bob.math.double === "function") &#123;	
		//works if bob is present and is a function
		var newNum = bob.math.double(oldNum);
	&#125; else &#123;
		//if bob is not present, provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This seems a lot longer given the possibilities of nested objects, but doing it this way also prevents the issue of same-named objects clobbering each other and sneaking in to create errors. If you are really confident with your code and have no outside workers/code coming in, you could skip the middle statements and just test for the parent object.</p>

<p>There we have it. This method of function existence checking has saved me lots of time and has created some interesting idioms for projects where external code may or may not be present. Enjoy!</p>
      ]]></content>
    </entry>

    <entry>
      <title>Making Anonymous Functions and Closures Work in ActionScript 2.0</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/making_anonymous_functions_and_closures_work_in_actionscript_20" />
      <id>tag:studiokoi.com,2008:blog/1.39</id>
      <published>2008-08-26T05:35:01Z</published>
      <updated>2008-08-25T22:12:23Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="Flash&#45;ActionScript"
        scheme="http://studiokoi.com/code/category/Flash-ActionScript"
        label="Flash&#45;ActionScript" />
      <content type="html"><![CDATA[
        <p>One of the most powerful idioms available in JavaScript is the anonymous function closure: e.g. (function(){})();. If you are unfamiliar with this, it simply creates an anonymous scope bubble that can be used to prevent automatic global variables, or trick JavaScript into allowing private variables. Unfortunately, this idiom isnt available in ActionScript 2.0. It simply doesnt work. (As of ActionScript 3.0, it works perfectly.)</p>
 
<p>This means that, on the surface, the only way to prevent time line variables from being constantly created is an init function of sorts. (ActionScript 2.0 has a pseudo global object which is the main time line of a movie level, and a totally global object named _global.) This also means that private variables are restricted to the creation of object classes. I personally get annoyed at times with classes in ActionScript. One of the things that has always bugged me with ActionScript 2.0 and the introduction of classes is that they are hard to make portable. (I work on no less than 3 computers in a single week, and 4-5 when on business trips, so portability is paramount to my work.) Rather than being able to simply include the classes in the same folder as the flash working file (*.fla), you must specify where on the computer the includes are. This is just annoying if you work on the file on several different computers. There are a couple of ways to avoid naming the class include folder on each computer, but they are as much of a pain as the default method. Fortunately, there is a solution.</p>

<p>To reiterate, while this works in JavaScript and ActionScript 3.0, it will not in ActionScript 2.0:
</p>
<pre class="brush: actionscript">(function()&#123;
	//statements
&#125;)();

var myFunc = (function()&#123;
	var hiddenVar = "hidden";
	return function()
	&#123;
		return hiddenVar;
	&#125;
&#125;)();
hiddenVar		//undefined
myFunc.hiddenVar; 	//undefined
myFunc(); 		//returns "hidden"</pre>

<p>The good news about ActionScript 2.0 is that it retains the ability to pass anonymous functions as variables to another function. Like so:
</p>
<pre class="brush: actionscript">var myArray = [5,1,6,23,15];
var sortedArray = myArray.sort(function(a, b)&#123;
	return a - b;
&#125;);
trace(sortedArray); //returns [1, 5, 6, 15, 23]</pre>

<p>Knowing this, we can emulate anonymous function closures in ActionScipt 2.0. First we will create a global function that returns the function passed to it.</p>
<pre class="brush: actionscript">_global.closure = function(f)
&#123;
	return f;
&#125;</pre>

<p>To use it, you treat it the same as you would the parenteses in the javascript idiom:
</p>

<pre class="brush: actionscript">closure(function()&#123;
	//statements
&#125;)();</pre>

<p>Changing the name to something shorter will make this more practical and the code a little cleaner.</p>

<pre class="brush: actionscript">_global.&#36; = function(f)
&#123;
	return f;
&#125;

&#36;(function()&#123;
	//statements
&#125;)();</pre>

<p>Given this new ability, we can now apply anonymous closures to our script without littering the time line object with useless variables.</p> 

<p>Lets use a hypothetical situation to illustrate how we might use the anonymous closure. In this script, we want to make 5 buttons that each need to trace their respective number when you click them. We could code each button individually, but that is messy and doesn't promote good code reuse. Instead, lets make a loop that makes all the buttons work, in addition to making it easier to add more buttons.</p>

<pre class="brush: actionscript">for (var i = 1; i &lt;= 5; i++)
&#123;
	//for each button
	this["click" + i + "_btn"].onPress = &#36;(function(n)&#123;
		//return a function that has access to n via
		// a closure
		return function()
		&#123;
			//trace the number passed to the parent closure
			trace(n);
		&#125;
	&#125;)(i); //pass in current loop iteration for caching
&#125;</pre>

<p>Now when you press click3_btn, it will trace '3' and click5_btn, '5'. In this way, we avoid creating useless variables inside each button, and we didn't have to create a singular use function.</p>

<p>Earlier I mentioned my slight distaste for how classes were implemented in ActionScript 2.0. Let me first caveat this statement by saying they are extremely useful and are wonderful for individuals or teams that have good version networks and servers. Just for myself and the smaller applications I write, I prefer portable objects. Lets see how we would write a singleton object with private variables and functions:</p>

<pre class="brush: actionscript">var bob = &#36;(function ()
&#123;
	//---------------------------
	//private variables
	var secret = "you found me";
	//---------------------------
	//private functions
	function compare(a, b)
	&#123;
		return a &gt; b;
	&#125;
	//---------------------------
	//constructor
	var Bob = &#123;
		//---------------------------
		//public members/variables
		works		:true,
		getSecret	:function()
		&#123;
			return secret;
		&#125;,
		getCompare	:function(a, b)
		&#123;
			return compare(a, b);
		&#125;
	&#125;;
	//---------------------------
	//return object
	return Bob;
&#125;)();
//test
trace(typeof bob) 		//returns object
trace(bob.works);		//returns true
trace(bob.getSecret());		//returns the string: you found me
trace(bob.secret);		//returns undefined
trace(bob.getCompare(1, 2));	//returns false
trace(bob.compare(1, 2));	//returns undefined function</pre>

<p>As you can see with the tests, we have a singleton object with private functions and variables as well as public methods and members. With a little work, using the prototypal inheritance method, we can make this a reusable pseudo class:</p>

<pre class="brush: actionscript">var Bob = &#36;(function ()
&#123;
	//---------------------------
	//private variables
	var secret = "you found me";
	//---------------------------
	//private functions
	function compare(a, b)
	&#123;
		return a &gt; b;
	&#125;
	//---------------------------
	//constructor
	var Bob = function ()
	&#123;
		//---------------------------
		//public members/variables
		this.works = true;
	&#125;;
	//---------------------------
	//public methods
	Bob.prototype.getSecret = function()
	&#123;
		return secret;
	&#125;;
	Bob.prototype.getCompare = function(a, b)
	&#123;
		return compare(a, b);
	&#125;;
	//---------------------------
	//return constructor
	return Bob;
&#125;)();
//invoke
var mybob = new Bob();
//test
trace(typeof Bob);		//returns function
trace(typeof mybob);		//returns object	
trace(mybob.works);		//returns true
trace(mybob.getSecret());	//returns the string: you found me
trace(mybob.secret);		//returns undefined
trace(mybob.getCompare(1, 2));	//returns false
trace(mybob.compare(1, 2));	//returns undefined</pre>

<p>So, with a single global function, we can bring the magic of anonymous function closures to ActionScript 2.0. Enjoy!</p>
      ]]></content>
    </entry>

    <entry>
      <title>Parsing a nested or name spaced object from a string in ECMAScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/parsing_a_nested_or_name_spaced_object_from_a_string_in_ecmascript" />
      <id>tag:studiokoi.com,2008:blog/1.23</id>
      <published>2008-01-10T05:37:54Z</published>
      <updated>2011-05-17T11:14:56Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>Often times when I am making dynamic scripts in Flash or JavaScript, I want to call an object method using a string. It may be a situation where I am stuck using <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary372.html" title="ActionScript Dictionary: fscommand">fscommand</a> (due to a customer request of a Flash version &lt;8) or just writing script with script.</p>

<p>The problem that comes with this method is the advent of ActionScript 3 with Flash CS3/Flex 2 and the rising use in namespaces by JavaScript developers (myself included). Both encour a heavy usage of object methods instead of one-off functions. Dynamically calling singleton functions is easy, you can just use subscript notation, e.g. object[&#8216;member/method&#8217;]. What you can&#8217;t do with this method is pass it any dot syntax and expect it to work e.g. object[&#8216;subobject.method&#8217;]. The subscript notation is only meant to work one level. So the previous example won&#8217;t work. In order to fix this issue and to make sending object methods/members in a single string a little easier, I wrote a function that takes a string and a base object (the default is the window object if no object reference is passed) and returns the method/member. (I know at this point that some will simply direct me to ECMAScript&#8217;s built in eval() function, but I personally avoid using it at all costs as it can have unintended, and unsecure results. I&#8217;ll let <a href="http://javascript.about.com/library/bleval.htm" title="About.com: Alternatives to eval">Stephen Chapmen tell you</a> because this article is about something else.)
</p>

<p>The function is executed somewhat simply by splitting the string at the dots and adding them as subscripts to one another in order. However, there are some other pieces to it that make it a little more friendly to mistakes and general usage.</p>

<p><pre class="brush: javascript">function parseNameSpace(s , o)
&#123;
	//default to window if no object sent
	var w = o || window, a;
	
	//reutrn if parsing not necessary or not a method
	if ( s.indexOf('.') == -1 )
	&#123;
		return (typeof w[s] === "undefined") ? false : w[s] ;
	&#125;
	
	//make array for looping through
	a = s.split('.');
	
	//run though members / methods
	for (var i = 0,l = a.length; i &lt; l; i++)
	&#123;
		w = w[a[i]];
	&#125;
	
	//return object if it is valid, or return false
	return (typeof w === "undefined") ? false : w ;
&#125;</pre></p>

<p>The function takes two variables, first the string that you want to parse to an object member, and the second optional base object. The first variable w looks for the object &#8220;o&#8221; and if not found, defaults to &#8220;window&#8221; which is the default parent object of browser based JavaScript. (You could change it to &#8220;this&#8221; and it would work in ActionScript as well). Second, we check to see if the passed string has any dots in it. If not, we check to see if it is a regular function. This way you could use this function as a catch all even if you aren&#8217;t always passing nested functions. If it isnt a member of the window object, false is returned. If it does have dots, we split them into an array, and loop through it, making each a member of the previous using the subscript notation. Finally we check to see if the result is valid, and we return false if it isn&#8217;t, or a reference to the object itself.</p>

<p>Let&#8217;s take a look at a simple way to use it. Lets say we have an object literal with a subobject, and a method inside that.</p>

<p><pre class="brush: javascript">var obj = &#123;
	innerObj: &#123;
		func: function()&#123;
			return "worked";
		&#125;
	&#125;
&#125;</pre></p>

<p>Then we retrieve it via string with the function.</p>

<p><pre class="brush: javascript">var objFunc = parseNameSpace("obj.innerObj.func");
alert(objFunc()); //shows "worked"</pre></p>

<p>This should work most places as long as you are mindful of function scope. Enjoy!</p>
      ]]></content>
    </entry>


</feed>
