Lua for Flash

flash

Why do you need Lua?
Lua is a powerful, fast, lightweight, embeddable scripting language. It combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is ideal for configuration, scripting, and rapid prototyping. Lua is extremely popular among game developers.

Introduction to LuaAlchemy
Lua has been ported from C++ to Flash Platform with Crossbridge compiler. So, you can download the latest swc file here and connect it to your project. Now, you can create a main LuaAlchemy object.

With LuaAlchemy object you can:
– Define global Lua and as3 variables
– Synchronously call a global Lua function
– Supply a ByteArray as a file in Lua
– Run Lua scripts from strings
– Run Lua scripts from virtual file system

How do you can to operate with as3 objects inside Lua scripts?
There are two ways:
Low level calls to the AS3 interface
LuaToAS3Sugar
I prefer to use sugar interface because it’s more readable.

Lua virtual file system
Also, often you need to use a lua virtual file system, where you can store your assets, lua scripts and access to it through lua functions like loadfile(), dofile(), require() you can read more about it here(CoreLuaLibraries) and here(AutoAssets). I will provide a simple example which explains how to do that inside as3.
Let’s write a simple Lua file and write/embed it in luaBytes ByteArray in as3 for the next usage

-- Lets write global lua string foo and print it
foo = "loaded"
print(foo)

AS3:

var lua:LuaAlchemy = new LuaAlchemy();
//place lua file in virtualFilesystemRoot default is "builtin://"
lua.supplyFile("builtin://test.lua", luaBytes);
//you can run it
lua.doFile("builtin://test.lua");//trace loaded
//you can access this file through lua script
//so lets run a simple lua code
lua.doString('dofile("test.lua")');//trace loaded
//foo is global, so you can access it like that from different lua code
lua.doString("print(foo)");//trace loaded

Additional Links:
Lua for ActionScript Developer
All Lua Alchemy Documentation
How to work with as3 objects in lua?
Extended as3 in lua
Lua Alchemy API)
Trending Lua repositories on GitHub today

I think it’s really great to have a such nice opportunity to use Lua in Flash Platform, because now you can easily equip your game tools with Lua script support!

P.S. it was really surprising for me to know that you can extend Adobe Photoshop Lightroom with Lua

SergeyGonchar
flash-developer
Visit Gonchar Website.

2 Responses to “Lua for Flash”

  1. James says:

    Good article, the Sugar version does look very nice!

    I have not used Lua before, but of course heard about it…
    …how does its performance impact a mobile game?

    I would assume it would be a bit slower than running code directly from the swf right?

  2. Amit Shvil says:

    What are the use case? Sergey Gonchar what are you using this cool thing for.

Leave a Reply

×
%d bloggers like this: