<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lua &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/category/lua/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Mon, 08 Jul 2013 14:42:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>Lua &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>One Game A Month &#8211; March Postmortem: Manifest Crystal</title>
		<link>https://jessewarden.com/2013/04/one-game-a-month-march-postmortem-manifest-crystal.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 01 Apr 2013 13:40:14 +0000</pubDate>
				<category><![CDATA[Lua]]></category>
		<category><![CDATA[1gam]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[coronasdk]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[onegameamonth]]></category>
		<category><![CDATA[programming]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=3520</guid>

					<description><![CDATA[I&#8217;ve entered into the One Game a Month party. It&#8217;s like Ludum Dare, a challenge to make, and most importantly FINISH, a game in a set amount of time based on a theme. What makes #1GAM unique is you have an entire month and it spans an entire year. They have a thriving Twitter and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve entered into the <a href="http://www.onegameamonth.com/">One Game a Month</a> party. It&#8217;s like <a href="http://www.ludumdare.com/compo/">Ludum Dare</a>, a challenge to make, and most importantly FINISH, a game in a set amount of time based on a theme. What makes #1GAM unique is you have an entire month and it spans an entire year. They have a thriving <a href="https://twitter.com/search?q=%231gam%20%23onegameamonth&amp;src=hash">Twitter</a> and <a href="https://plus.google.com/communities/117275686212402755276">Google+ group</a>.</p>
<p>I&#8217;ve entered strictly for learning purposes and to see if I can actually finish something. Game development is surprisingly very different from application development, and it&#8217;s nice to feel really stupid again.</p>
<p><span id="more-3520"></span><strong>Synopsis</strong></p>
<p>An role playing game in the play and art style of 1996&#8217;s Final Fantasy 6 released in 1994.</p>
<p>A group of 11 or so individuals come into contact with Manifest Crystals and come to terms with their new powers. Â They learn the true depth of humanity&#8217;s crystal exploitation as well as the ecological impact and purpose of crystals. Â They are tenuous allies with the military/government as they learn the truths, overcome some planetary threats, and work to stop the main antagonist.</p>
<p><strong>Manifest Crystal Goals</strong></p>
<p>I wanted to do an RPG, badly. It&#8217;s the whole reason I wanted to work for <a href="http://na.square-enix.com/">Squaresoft</a> when I grew up. However, I really struggled to get excited about <a href="http://getmoai.com/">Moai</a>. While they have grids and <a href="http://getmoai.com/docs/class_m_o_a_i_path_finder.html">pathfinding</a> built in, I just didn&#8217;t see how the low-level API helped me; what I&#8217;m doing is not that sophisticated in terms of GUI. <a href="http://www.giderosmobile.com/">Gideros</a> had aÂ similarÂ fate when with their simplistic API that was missing some things I wanted from <a href="http://coronalabs.com">Corona</a>. I looked at them specifically because their API is familiar and had bitmap features, like Moai, which Corona doesn&#8217;t have. Some tests I did of Corona last year moving large masked bitmaps were promising, so I figured I&#8217;d give her a go.</p>
<p><strong>Actual Results</strong></p>
<p>March was a no show. Not even a build.</p>
<p>First week I was extremely burnt out of #1GAM. I worked really hard for my February entry, so spent the first week fixing burn out: which means no computer.</p>
<p>Additionally, March is when taxes are due in the USA, so that was a lot of work as well aside from the normal quarterly state and federal filings</p>
<p>Also work was pretty rough in March. Lots of challenges in the code, working multiple projects with multiple developers; huge cognitive load that made me collapse at night with zero energy left for #1GAM. March is also the month when companies start hiring to close their 1st quarter budget or get plans for 2nd quarter, so fielded a lot of sales calls/emails.</p>
<p>Finally, I&#8217;ve been playing with my diet for fitness and health goals. That means 40% protein, 30% fats, 10% carbs + a 300 calorie deficit. This means 3 weeks of adjusting my head to the lack of carbs it needs to produce mad serotonin + being distracted by being hungry. That and I still struggle with getting enough sleep. Grumpy, tired me.</p>
<p>Not the best combination to tackle my hardest game challenge yet. At the end of the day, I prioritize work 1st, working out 2nd, and #1GAM 3rd so he&#8217;s the first to get cut from a busy life.</p>
<p><strong>What Went Wrong</strong></p>
<p>First, this is the 2nd time I attempted this game. The first was about 3 years ago. I picked the best people in the industry I knew at the time that I&#8217;d kill to work with, sent them a mass email, and laid out my plan. It was clear I could inspire, but not get people to actually do what I wanted them to do. Additionally, not sure everyone bought into the idea, and I think everyone wanted some more organization around tasks &amp; milestones. That, and doing a game on the side is asking a lot of people who are A players in this industry and already have a ton going on. You need to provide key incentives. I think.</p>
<p>I tried to learn from that mistake and organize things a bit more,Â especiallyÂ since what I learned fromÂ JanuaryÂ and March is that even spending 10 minutes to write, organize, and prioritize high level tasks has a HUGE impact down the line. I know what I&#8217;m supposed to be doing, if I hit a brick wall or just get tired of a task, I can jump to another one, and if scope becomes a problem it&#8217;s easier to see what I can cut vs. keep. It wasn&#8217;t enough, though; I probably should have spent 2 days vs. 10 minutes. An RPG, even a small one that&#8217;s story driven like mine, requires a ton more upfront work as I&#8217;ve found. Twice, hah!</p>
<p>At this point I&#8217;ve been content producing horrible game art myself. However, I misjudged just how much and the varied types I need for this game. I struggled to reduce the scope because evenÂ minimalistÂ design still has the responsibility to evoking the emotions in the player the story is trying to convey and key junctures. I could probably pull it off, but without a full list knowing what was needed, and where, it was too much work for me and sabotaged my momentum on art days.</p>
<p><strong>What Went Right</strong></p>
<p>I got a lot of great code out of this. Although I only put in maybe 10, 1 hour days, I now have a ton of great converted from ActionScript to Lua and new code I can use to try again later this year.</p>
<p>I also finally managed to get a highly level scalable battle system that I hired aÂ mathematicianÂ to verify.</p>
<p>I really enjoyed playing with various menu systems on mobile devices, and built my 2nd <a href="https://www.google.com/search?q=radial+menu&amp;hl=en&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ei=9Y9ZUezxLof69gSil4CQAw&amp;ved=0CAoQ_AUoAQ&amp;biw=1311&amp;bih=726">pie / radial menu</a>, taking many cues from <a href="http://en.wikipedia.org/wiki/Secret_of_Mana">Secret of Mana</a>. I still haven&#8217;t gotten the <a href="http://www.swype.com/">Swype</a> esque way of using it down, but it&#8217;s good enough even with just taps.</p>
<p>My tile engine performed just fine with large textures on crappy Android devices so that was promising.</p>
<p>Finally, I learned yet again a ton whilst coding and designing and writing. Just a lot of little things that all add up to make even this failure totally worth it.</p>
<p><strong>Key Takeaways</strong></p>
<p>I&#8217;ve yet to see myself over plan. It&#8217;d be nice to make that mistake and see results.</p>
<p>I really should put a budget together for an artist to handle most of the game art, and I can handle the GUI well ahead of the start date at least to get discussions going. It was such a huge percentage of my time this month and required some iterations to get right both for story and technical reasons. I fail to see how I can do it all myself. Reducing scope is out of the question, so maybe I can write a different story to test all the engine + code out first for aÂ separateÂ game, much like <a href="http://www.gametrailers.com/full-episodes/ucf5sb/gt-retrospectives-final-fantasy-retrospective--part-iv">Square did back in 1995 (scrub to 11:45)</a> at Siggraph making 3D FF6 characters to test out the FF7 3D engine for the upcoming Playstation 1. It&#8217;d make a good tracer bullet, not sure how fun though, we&#8217;ll see.</p>
<p>Yet again I&#8217;ve proven even failures results in tons of good, reusable code and a lot of things learned.</p>
<p><strong>Conclusions</strong></p>
<p>I think I&#8217;ll postpone my next RPG attempt for June or August for a variety of reasons. First, I need some more practice getting teams to work together; would really rather tackle it NOT by myself even if it&#8217;s just an art + audio sub. Second, it&#8217;ll be summer then, and I&#8217;ll be outside more. While I&#8217;m taking Vitamin D supplements (yes, no dairy + no outside == deficient), by then the pool will be open and I&#8217;ll be taking the girls their daily. That and carbs will be 50% of my diet. Those&#8217;ll up the mood. Third, I&#8217;m burnt out on involved game mechanics, I need to fall back to my roots to get rejuvenated: app development.</p>
<p>April: A health and nutrition game both to educate people and get them eating better. While games like this exist, it&#8217;ll be more app like so that&#8217;s something I excel at, and it&#8217;ll help me to continue to learn about nutrition which I&#8217;ve been learning about on the side for awhile. Making this a game sounds fun.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Lua for ActionScript Developers: Crash Course</title>
		<link>https://jessewarden.com/2011/01/lua-for-actionscript-developers.html</link>
					<comments>https://jessewarden.com/2011/01/lua-for-actionscript-developers.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 25 Jan 2011 17:43:51 +0000</pubDate>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[programming]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2589</guid>

					<description><![CDATA[Skip Intro Preface I needed a break from Flex for mobile, and wanted to see if there were any other good application frameworks that allowed you to deploy to multiple devices beyond Adobe AIR. Tony Lukasavage had written about a few recently, and Matt Guest had written about his quick experience using Corona for games [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="http://jessewarden.com/2011/01/lua-for-actionscript-developers.html#zedispensergoeshere">Skip Intro</a></p>
<p><strong>Preface</strong></p>
<p>I needed a break from Flex for mobile, and wanted to see if there were any other good application frameworks that allowed you to deploy to multiple devices beyond Adobe AIR.  Tony Lukasavage had <a href="http://savagelook.com/blog/portfolio/appcelerator-vs-phonegap-vs-adobe-air">written about a few recently</a>, and Matt Guest had written about his q<a href="http://mattguest.com/2011/01/playing-with-corona/">uick experience</a> using Corona for games based on the <a href="http://news.yahoo.com/video/us-15749625/tween-tech-prodigy-23867645">buzz</a> around <a href="http://naygames.com/">Robert Nay</a>, the 14 year old who knocked Angry Birds out of the top mobile game slot via <a href="http://blog.anscamobile.com/2011/01/bubble-ball-and-corona-sdk-in-the-news/">Bubble Ball</a>.</p>
<p><span id="more-2589"></span>While <a href="http://unity3d.com/">Unity</a> has the best language on the planet, C#, I needed a break from lower level languages. Â In the past, <a href="http://rubyonrails.org/">Ruby</a> and <a href="http://www.djangoproject.com/">Python</a> were greatÂ reprievesÂ for doing smaller projects. Â In doing some mobile apps, I&#8217;ve noticed that for the scope of the project, sometimes 3 weeks or less, the verbose language actually gets in the way. Â So, I was looking for a higher level language, and <a href="http://www.lua.org/pil/index.html">Lua</a> in <a href="http://www.anscamobile.com/corona/">Corona</a> SEEMS to fit the bill, but I&#8217;m still learning. Â I liked how I could save a file in <a href="http://macromates.com/">TextMate</a> and and it would just refresh the iPhone/Android emulator. HOTNESS! Uber fast compared to mxmlc and &#8220;Building&#8230;&#8221; in Flash Builder, even when using pure AS3. Â The interpreted nature of Lua helps speed that up (I guess).</p>
<p><strong>Introduction</strong></p>
<p>I&#8217;ve only been reading up on Lua for 1 day, but here&#8217;s a quick crash course to get traditional ActionScript programmers up to speed with Lua concepts. Â If you&#8217;ve done any ActionScript 1, or even JavaScript, you&#8217;ll find this very familiar to traditional ECMA concepts. Â If you&#8217;re a Java/C guy coming to Flex and now reading this, it may be a little weird.</p>
<p>I&#8217;m still learning the OOP &amp; packages Lua stuff, so will post that in a later article. Â In reading the docs, it&#8217;s pretty clear OOP and packages aren&#8217;t really something the original language designers figured you&#8217;d actually do, so it seems like a ton of work, more than it took in AS1, to get inheritance and packages.</p>
<p><strong>WARNING</strong>: This guide was written primarely to help me learn Lua and have all the common comparisons on one page. Â I&#8217;m sure it has errors and misconceptions; if I get railed in the comments, I&#8217;ll update this post as soon as possible. Â Here there be dragons, bitches!</p>
<p><a name="zedispensergoeshere"></a><strong>Getting Started</strong></p>
<p>If you&#8217;re on a Mac, the best thing to do is go download &amp; install <a href="http://www.anscamobile.com/corona/">Corona</a> + <a href="http://macromates.com/">TextMate</a>, and then install the <a href="http://www.ludicroussoftware.com/corona/corona-bundle-for-textmate/">Corona Bundle for TextMate</a>. Â For Windows users, you can <a href="http://blog.anscamobile.com/2011/01/corona-sdk-is-now-on-windows/">check out more</a> on their blog.</p>
<p><strong>Output</strong></p>
<p>To show output from your code in ActionScript for the Flash IDE&#8217;s console, or Flash Builder&#8217;s console, you use trace:</p>
<pre lang="actionscript">trace("Hello World!");</pre>
<p>In Lua, you use print:</p>
<pre lang="lua">print("Hello World!")</pre>
<p>You&#8217;ll notice there is no semi-colon used in Lua.  Like ActionScript they are optional, but most code I&#8217;ve seen doesn&#8217;t use them.  I&#8217;ve only met 1 ActionScript coder that didn&#8217;t use semi-colons.</p>
<p>There are also no brackets {} in Lua, similar to Python, although the whitespace isn&#8217;t as strict.</p>
<p><strong>Comments</strong></p>
<p>In ActionScript, a single line comment is //:</p>
<pre lang="actionscript">// This is a comment ActionScript</pre>
<p>In Lua, a single line comment is: &#8212;</p>
<pre lang="lua">-- This is a comment in Lua</pre>
<p>A multi-line comment in ActionScript starts with /* and ends with */:</p>
<pre lang="actionscript">/*
This is a
multiline comment
in ActionScript
*/</pre>
<p>In Lua, it starts with &#8211;[[ and ends up ]]&#8211;:</p>
<pre lang="lua">--[[
This is a
multiline comment
in Lua
]]--</pre>
<p><strong>Variables</strong></p>
<p>In ActionScript 1, this was a global variable:</p>
<pre lang="actionscript">_global.foo = "bar";</pre>
<p>In Lua, this is a global variable:</p>
<pre lang="lua">foo = "bar"</pre>
<p>In ActionScript 3, you usually have to utilize the Singleton design pattern or a default namespace class to get globals:</p>
<pre lang="actionscript">package
{

	public class MyGlobals
	{

		public var foo:String;

		private static var _inst:MyGlobals;

		public function get instance():MyGlobals
		{
			if(_inst == null)
				_inst = new MyGlobals();

			return _inst;
		}
	}
}

// then to use
MyGlobals.instance.foo = "bar";</pre>
<p>&#8230;or a public static variable on MyGlobals:</p>
<pre lang="actionscript">package
{
	public class MyGlobals
	{
		public static var foo:String;
	}
}

// then to use
MyGlobals.foo = "bar";</pre>
<p>In ActionScript 3, un-initialized variables on non-dynamic objects such as classes such as Strings or other by reference variables are null:</p>
<pre lang="actionscript">trace(foo); // null
foo = "bar";
trace(foo); // bar</pre>
<p>Lua uses nil:</p>
<pre lang="lua">print(foo) --> nil
foo = "bar"
print(foo) --> bar</pre>
<p>To remove a reference on a strongly-typed object in ActionScript 3, you set the variable to null:</p>
<pre lang="actionscript">myArray = [1, 2, 3];
myArray = null;</pre>
<p>In Lua, you set it to nil:</p>
<pre lang="lua">myNumber = 10
myNumber = nil</pre>
<p>Notice I used a Number in Lua.  In ActionScript 1, you could do that since all were variants, but in AS3, you can&#8217;t set a Number to null, only another Number or NaN.</p>
<p>Lua (I think) has it&#8217;s own garbage collection like ActionScript 1 and 3 do, thus they both use null and nil to decrement the reference count on objects.  Both have similar rules for immutable primitives, like String and Number always creating new variables, and this copying by value when you create new ones:</p>
<pre lang="actionscript">var a:String = "moo";
var b:String = a;
a = "whoa";
trace(a); // whoa
trace(b); // moo</pre>
<p>Lua is the same way.</p>
<p>The reverse is true for Objects that use by ref such as Arrays/Lists and other Objects.</p>
<pre lang="actionscript">var a:Array = [1, 2, 3];
var b:Array = a;
a.pop();
trace(a); // 1,2
trace(b); // 1,2
trace(a == b); // true</pre>
<p>So, while ActionScript 3 has certain rules for primitives such as String, Number, int, and uint, in Lua you can just set it&#8217;s String and Number (it only has Float) to nil.</p>
<p><strong>Types</strong></p>
<p>In ActionScript 1, most everything was a variant.  In ActionScript 3, we have a true type system.  In Lua, everything is basically a variant.  In AS1, if you wanted to figure out the type of something, you&#8217;d use typeof:</p>
<pre lang="actionscript">var foo = "bar";
trace(typeof(foo)); // bar
var foo = 10;
trace(typeof(foo)); // number
trace(typeof(typeof)); // function</pre>
<p>In Lua, you use type:</p>
<pre lang="lua">foo = "bar"
print(type(foo)) --> string
foo = 10
print(type(foo)) --> number
print(type(type)) --> function</pre>
<p><strong>Booleans &amp; if tests</strong></p>
<p>Keep in mind, nil and false always equate to false. Everything else is true. The use of 0 and &#8220;&#8221; are considered true in Lua, and in ActionScript.  Sometimes people will use if in ActionScript to test for true or if a variable is not null:</p>
<pre lang="actionscript">if(foo)
{
  trace("foo is: " + foo); // bar
}
else
{
   trace("foo is null.");
}</pre>
<p>Similar in Lua:</p>
<pre lang="actionscript">if foo then
	print("foo is: " .. foo)
else
	print("foo is nill")
end</pre>
<p><strong>Concatenation</strong></p>
<p>Notice in ActionScript, + is used for concatenating everything in trace, and ActionScript is smart enough to coerce and/or call toString() on certain Objects.</p>
<pre lang="actionscript">trace("foo " + "bar"); // foo bar</pre>
<p>In Lua, you use ..</p>
<pre lang="lua">print("foo " .. "bar") --> foo bar</pre>
<p><strong>Numbers/Floats</strong></p>
<p>Numbers in Lua are similar to Numbers in ActionScript 1; they are floats (decimals).  There are no ints or uints.</p>
<p><strong>Tables vs Objects</strong></p>
<p>Tables are the what Lua calls Objects.  They have nearly the exact same syntax, although their constructors are completely different and have a ton of syntactic sugar in Lua.  They&#8217;re basically associative arrays.  You can use any value as the key in Lua, excluding nil.</p>
<pre lang="actionscript">var a:Object = {};
var k:String = "x";
a[k] = 10;
trace(a["x"]); // 10
trace(a.x); // 10</pre>
<pre lang="lua">a = {}
k = "x"
a[k] = 10
print(a["x"]) --> 10
print(a.x) --> 10</pre>
<p>To remove slots in ActionScript, you use delete:</p>
<pre lang="actionscript">delete a.x;</pre>
<p>In Lua, you just set it to nil:</p>
<pre lang="lua">a.x = nil</pre>
<p><strong>Math</strong></p>
<p>Math operations are about the same using +, -, *, / and standard math precedence/order of operations including parentheses ()&#8230; sort of. You can <a href="http://www.lua.org/pil/3.5.html">see the precedence in the docs</a>.</p>
<p><strong>Relational Operators</strong></p>
<p>Lua has about the same operators as ActionScirpt excluding &#8220;not equal&#8221;.</p>
<pre lang="actionscript"> <   >   <=  >=  ==  !=</pre>
<pre lang="lua"> <   >   <=  >=  ==  ~=</pre>
<p>Notice the last one.</p>
<p><strong>Logical Operators</strong></p>
<p>ActionScript has:</p>
<pre lang="actionscript">&& // and
|| // or
!= // Borat says, "NNNooott!"</pre>
<p>Lua has:</p>
<pre lang="lua">and --> and
or --> or
not --> not</pre>
<p>So, from the Lua docs, here&#8217;s ActionScript:</p>
<pre lang="actionscript">trace(4 && 5);         // 5
trace(null && 13);         // null
trace(false && 13);         // false
trace(4 || 5);         // 4
trace(false || 5);         // 5</pre>
<p>And Lua:</p>
<pre lang="lua">print(4 and 5)         --> 5
print(nil and 13)      --> nil
print(false and 13)    --> false
print(4 or 5)          --> 4
print(false or 5)      --> 5</pre>
<p><strong>Assignments and Statements</strong></p>
<p>ActionScript and Lua have a similiar syntax for statements although ActionScript has more helper shortcuts like +=, ++, etc.</p>
<pre lang="actionscript">var a:Number = 1;
a = a + 1;
trace(a); // 2
a++;
trace(a); // 3</pre>
<pre lang="lua">a = 1
a = a + 1
print(a) // 2
a = a + 1
print(a) // 3</pre>
<p>You can also do single line with multiple variables; while un-readable to me, it actually comes into play when you have functions returning multiple values and error handling as you&#8217;ll see later.</p>
<pre lang="lua">a, b = 10, 2*x</pre>
<p>For example, assuming getResults() returns 2 values instead of the standard 1 in ActionScript, you can get the first and second via:</p>
<pre lang="lua">a, b = getResults()</pre>
<p>Yes, craziness.</p>
<p><strong>Local Variables</strong></p>
<p>Local variables in ActionScript:</p>
<pre lang="actionscript">var i:Number = 0;

function foo()
{
   trace(i); // 0
   var i:Number = 23;
   trace(i); // 23
}</pre>
<p>And in Lua:</p>
<pre lang="lua">i = 0
local i = 1</pre>
<p>Local variables are stricter in scope in Lua than in ActionScript.  They are similar to how they are (I think) in C, where it&#8217;s &#8220;block based&#8221;.  In ActionScript, the local variable is local to the entire function whereas in Lua, it&#8217;s local only to the current block it&#8217;s in, such as the then/else part of the if then statement.  Finally, in both languages, local variables are faster to access.</p>
<p>An example of local scope in Lua is a while loop:</p>
<pre lang="lua">x = 10
local i = 1 --> local to chunk
while i < 2 do
   local x = i * 2 -- local to the while body   
   print(x) --> 2, 4, 6, 8, ...
   i = i + 1
end</pre>
<p>The locals, like in ActionScript, aren&#8217;t actually created until you initialize them, so this makes for more efficient code.</p>
<p><strong>Control Structures</strong></p>
<p>Lua has the standard <strong>if</strong>, <strong>while</strong>, <strong>for</strong>, and <strong>repeat</strong> statements.  The difference is the <strong>if</strong>, <strong>while</strong>, and <strong>for</strong> need a corresponding <strong>end</strong> for the statement.  The <strong>repeats</strong> use an <strong>until</strong> statement.</p>
<p>Here&#8217;s a simple if statement in ActionScript:</p>
<pre lang="actionscript">if(a < 0)
{
   a = 0;
}</pre>
<p>And Lua:</p>
<pre lang="lua">if a < 0 then a = 0 end</pre>
<p>... or:</p>
<pre lang="lua">if a < 0 then
   a = 0
end</pre>
<p>Here's an if else statement in ActionScript:</p>
<pre lang="actionscript">if(a < b)
{
   return a;
}
else
{
   return b;
}</pre>
<p>And in Lua:</p>
<pre lang="lua">if a < b then
   return a
else
   return b
end</pre>
<p>...that too can be written on one line.</p>
<p>Like Python, Lua has elseif:</p>
<pre lang="lua">if value == "north" then
   return y  - 1
elseif value == "south" then
   return y + 1
elseif value == "east" then
   return x + 1
elseif value == "west" then
   return x - 1
else
   error("invalid direction, yo!")
end</pre>
<p>Notice we have the standard == to test for equality.  The common way to report errors is the error function; we'll get to him in a bit.</p>
<p><strong>Loops</strong></p>
<p>A quick note about loops.  In ActionScript, the first index of an Array or Vector is 0.  In Lua, it's whatever you want, but the convention is 1.  You can use 0 if you really want to, but a lot of the existing libraries may not work since they follow the 1 convention.  Also there isn't a concept of "Array.length" in Lua.  The first item found that has nil is considered to be "end" of the Array/List/Table.</p>
<p><strong>While Loop (and Arrays)</strong></p>
<p>For you while fans, here's one in ActionScript:</p>
<pre lang="actionscript">var i:int = 0;
while(list[i])
{
   trace(list[i]);
   i++;
}</pre>
<p>And in Lua:</p>
<pre lang="lua">local i = 1
while list[i] do
   print(list[i])
   i = i + 1
end</pre>
<p>Notice Lua starts with 1 whereas ActionScript starts with 0.  Also notice the while loop in Lua is testing if list[i] is not equal to false or nil.  The way Arrays (in this case a simple table acting as an associative array) work for most looping operations is you test for nil in them.  If it finds nil, it assumes it is the end of the array/list.</p>
<p><strong>For - 2 Types</strong></p>
<p>There are 2 types of for loops.  For loops are similar to ActionScript, but the syntax is quite different.  Sometimes smaller loops are written on 1 line.  You'll constantly see this in Lua because of it's Functional bent, a lot of people try to write as terse as syntax as possible.  If you come from a Java/ActionScript 3 only background, you'll want to spread it out more.  I'll do both below.</p>
<p>Lua's numeric version of for loop works in pseudo code like this:</p>
<pre lang="lua">for var=start,end,optionalIncrement do
   something
end</pre>
<p>You don't need to include the increment; if you don't, it'll assume 1.  Most for loops I've seen in ActionScript always use 1 anyway.</p>
<p>Here's how we loop through 1 to 10 in ActionScript:</p>
<pre lang="actionscript">for(var i:int=1; i < 11; i++)
{
   trace(i);
}</pre>
<p>Here's how we do the same in Lua:</p>
<pre lang="lua">for i=1,10,1 do print(i) end</pre>
<p>...or:</p>
<pre lang="lua">for i=1,10 do print(i) end</pre>
<p>...or even:</p>
<pre lang="lua">for i=1,10,1 do
   print(i)
end</pre>
<p>There are some strange things too.  The var, or i in this case, is a local variable to the for loop.  After the loop is done in ActionScript, you can reference it, but not in Lua.</p>
<p>Also, functions/expressions in the for loop itself for start/end/increment are only run once where as in ActionScript, the test &amp; increment are done each loop.</p>
<p>Like ActionScript, if you want to abort the mofo, use break.  If you want to break it down, use <a href="http://soundcloud.com/dj-icey">DJ Icey</a>.</p>
<p>The generic for is like a for var n or a for each in ActionScript where you iterate over properties of an Object.  This gets pretty deep in Lua, and they have a TON of different ways one can write iterators, using closures, coroutines, etc.  I encourage you to briefly <a href="http://www.lua.org/pil/4.3.5.html">read the docs on generic for</a> and hit the <a href="http://www.lua.org/pil/7.html">advanced stuff</a> (advanced for me, heh) if you're into that kind of thing (*cough* Python developers *cough*).</p>
<p><strong>Break and Return Placement</strong></p>
<p>While break and return are similar to ActionScript, their placement is more strict.  Both have to be right before the last part of a block (right above end, else, or until).</p>
<p><strong>Functions</strong></p>
<p>Functions in Lua are just like they are in ActionScript with some subtle rules about usage you can <a href="http://www.lua.org/pil/5.html">read more on</a>.  What I want to focus on is multiple return values which plays into how you do error handling/logging in Lua if you come from a Flash background.</p>
<p>It's called unconventional in the docs, but when all functions that run in protected mode (more on that later), return errors as the 2nd parameter, that's not unconventional, that's conventional.</p>
<p>Anyway, check out how the find string function looks in Lua:</p>
<pre lang="lua"> s, e = string.find("hello Lua users", "Lua")
print(s, e)   -->  7      9</pre>
<p>The find gets the first index where it occurs and ends or nil if it can't find it.  Notice how the first result is in s, and the second is in e.  To do this yourself, you just return 2 values like so:</p>
<pre lang="lua">function fooByTwo()
   return 1, 2
end

uno, dos = fooByTwo()</pre>
<p><strong>Variable Number of Arguments</strong></p>
<p>Lua has rest parameters like ActionScript has as well:</p>
<pre lang="lua">function showNames (...)
   for i, name in ipairs(arg) do
      print(i .. ":name=" .. name .. "\t")
   end
end</pre>
<p>Notice the <strong>arg</strong> variable is a predefined variable in functions, much like <strong>arguments</strong> was in ActionScript 1.  In ActionScript 3, we can name it whatever we want:</p>
<pre lang="actionscript">function showNames(... names)</pre>
<p>Finally, you'll notice <strong>ipairs</strong> is used a lot as a sort of default iterator for loops.</p>
<p><strong>Function Scope</strong></p>
<p>You can read more about lexical scoping, closures, and all the other Functional stuff if you want, but I wanted to focus on Scope because it's bloody AS1's thisThing.owner/mx.utils.Delegate all over again.  If you don't remember what I'm talking about, or you have no context, <a href="http://www.bit-101.com/blog/?p=525">Keith talks about it</a> and how to get around ActionScript 1's scoping challenges via the Activation Object and Mike Chambers elaborates on how <a href="http://www.mikechambers.com/blog/2008/10/08/function-closures-and-this-in-actionscript-3/">closures work in AS3</a>.</p>
<p>Before AS3, classes had their callbacks scoped to what object they were called from, not where they were defined; thus you had to give child objects pointers back to their parent classes.</p>
<p>Lua has the same deal with functions.  I'll elaborate more in a future OOP article since I'm still learning, but here's how it works.  Functions in Lua by default don't have a <strong>this</strong> or <strong>self</strong>.  Much like Python, you have to pass in scope in a generalized fashion.</p>
<p><strong>Static</strong></p>
<p>So... here's how you do a static method(sort of) in ActionScript:</p>
<pre lang="actionscript">package
{
	public class Bar
	{
		public static function foo(a:String):void
		{
			trace("passed in var: " + a);
		}
	}
}

Bar.foo();</pre>
<p>...and in Lua:</p>
<pre lang="lua">Bar = {}
function Bar.foo(a)
   print("passed in var: " .. a)
end
Bar.foo("Cow")</pre>
<p>In Lua, like AS1, you delete your class objects, however, thus if I made an instance, and tried to call it, it'd cause an error:</p>
<pre lang="lua">b = Bar
Bar = nil
b.foo("Test") --> Error</pre>
<p><strong>Instance Methods</strong></p>
<p>So how do we get "this" equivalent?  In 2 ways; it depends on how you call the function.  Remember, Functional people like carrying scope around like a magic gem... seems like a lot of work to me, but I grew into an OOP world so what do I know.</p>
<p>You'd refine the above to this:</p>
<pre lang="lua">function Bar.foo(self, a)
   print("passed in var: " .. a)
end</pre>
<p>Then, you can call it in 2 ways, the first manual way:</p>
<pre lang="lua">b = Bar;
b.foo(b, "test")</pre>
<p>Or the built-in way they have to do that for you:</p>
<pre lang="lua">b = Bar;
b:foo("test")</pre>
<p>Notice the colon instead of the dot.</p>
<p>If you remember Object.prototype in ActionScript 1 where you had to manually add this inside all functions, it's very similar.</p>
<p><strong>Classes</strong></p>
<p>I'll get into classes and packages later... they are whack compared to what I'm used too.  For now, here's 3 syntax variations you can do (this'll look familiar to you AS1 devs):</p>
<p>The object/table way:</p>
<pre lang="lua">Lib = {}
Lib.foo = function (x,y) return x + y end
Lib.goo = function (x,y) return x - y end</pre>
<p>Using the Lua table constructor way:</p>
<pre lang="lua">Lib = {
  foo = function (x,y) return x + y end,
  goo = function (x,y) return x - y end
}</pre>
<p>And the common way I've seen in Cornoa (I think):</p>
<pre lang="lua">Lib = {}
function Lib.foo (x,y)
   return x + y
end
function Lib.goo (x,y)
   return x - y
end</pre>
<p><strong>Errors</strong></p>
<p>Lua's runtime, at least from what I've seen in Corona, runs just like Flash Player 8 on down did.  If the original AVM has an error, it aborts the current function and/or related stack items, and tries its best to proceed.  You can run Lua where it'll output to the console (Terminal if on Mac), but you won't see the errors in your code unless you specifically trap/log them.</p>
<p>A common error check in ActionScript 3 is checking for null; since this is the one thing our mxmlc compiler (and the Flash IDE) isn't really good at finding since Flash often gets external data in it, and thus "garbage in, garbage out" comes into play.</p>
<pre lang="actionscript">if(UserFactory.getUser(xml) == null)
{
   throw new Error("Dude, our XML is whack, yo! ...or maybe our parsing code is lame.");
}</pre>
<p>Lua can do something similar:</p>
<pre lang="lua">if not UserFactory.getUser(xml) then error("Dude, our XML is whack, yo! ...or maybe our parsing code is lame.") end</pre>
<p>However, that's a pretty common operation in Lua, thus they have an <strong>assert</strong> function.  If assert gets a false or nil back from the function, it'll raise an error with the string you pass in the 2nd parameter:</p>
<pre lang="lua">user = assert(UserFactory.getUser(xml), "Failed to parse user."),</pre>
<p>If you don't raise your own error in functions, Lua will return <strong>nil</strong> by default.  Otherwise, you can call the built in <strong>error</strong> function, passing in the reason for the failure as a string, simliar to throw new Error("<a href="http://www.youtube.com/watch?v=30BvoBbrTxM">that blowed up real good</a>") in ActionScript 3.  You'll be able to see this in the console/Terminal.</p>
<p>Thus, the common way to play it safe is to use <strong>assert</strong>.  Remember before explaining how Functions can return 2 values, and by default will return the error, if any, as the 2nd parameter?  This works naturally with assert (example below from <a href="http://www.lua.org/pil/8.3.html">the docs</a>):</p>
<pre lang="lua">file = assert(io.open("no-file", "r"))
      --> stdin:1: no-file: No such file or directory</pre>
<p>Notice you didn't have to write a 2nd parameter in the error function, it'll return and print automatically via assert.</p>
<p><strong>Custom Error Handling</strong></p>
<p>Lua has a try/catch equivalent as well.  If you call error("Explosions") inside a Lua function, it can be caught via <strong>pcall</strong> which means "protected call".  Using pcall, it'll return true if all is well, and false if an error occurred.  In ActionScript, you'd go:</p>
<pre lang="actionscript">public function foo():void
{
	if(!allGoodInDaHoodDogwood)
	{
		throw new Error("ZOMG, Compton!");
	}
	else
	{
		return;
	}
}

try
{
	foo();
}
catch(err:Error)
{
	trace(err);
}</pre>
<p>In Lua:</p>
<pre lang="lua">function foo()
	if not allGoodInDaHoodDogwood then
		error("ZOMG, Compton!")
	else
		return
	end
end

if pcall(foo) then
	-- no errors in foo
	print "They SHOOTIN'!!!... aw made you look, you slave to a page in my rhyme book."
else
	-- foo threw an error
	print "foo blew up"
end</pre>
<p><strong>Stacktrace</strong></p>
<p>You can use</p>
<pre lang="lua">print(debug.traceback)</pre>
<p>to see the stacktrace up to the point of execution.</p>
<p><strong>Conclusion</strong></p>
<p>As we can see, Lua has a lot in common with ActionScript, specifically ActionScript 1, JavaScript, and ECMA in general.  There is much more to Lua than the above, and the above is just from 1 day of reading &amp; playing.  If you're not looking to totally rock your world when learning a new language, say <a href="http://jessewarden.com/2010/04/cocoa-chronicles-1-actionscript-vs-objective-c.html">ActionScript to Objective C</a>, then I encourage you to check out Lua, specifically using the Corona resources I stated at the top of this article.  When I figure this OOP and package stuff out, I'll write a follow up post.</p>
<p>Please feel free to post corrections in the comments; I'm obviously still new at Lua.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/01/lua-for-actionscript-developers.html/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
	</channel>
</rss>
