Categories
Corona SDK Lua OOP

EventDispatcher docs

Documentation has been added for EventDispatcher in LDoc format, generated from the source file.

Here’s the basic usage:

local EvtD = require "EventDispatcher"

local dispatcher = EvtD()

-- listener as table
local listener = {
   eventName = function(event, ...)
      print(event.name, event.target, event.source)
   end
}

-- listener as function
local function listener(event, ...)
    print(event.name, event.target, event.source)
end

dispatcher:addEventListener( "eventName", listener ) -- or
dispatcher:on( "eventName", listener )

dispatcher:once( "eventName", listener )

dispatcher:hasEventListener( "eventName", listener )

dispatcher:dispatchEvent( { name="eventName" } ) -- or
dispatcher:dispatchEvent( "eventName" ) -- or
dispatcher:emit( { name="eventName" } ) -- or
dispatcher:emit( "eventName" )

dispatcher:removeEventListener( "eventName", listener )

dispatcher:removeAllListeners( "eventName" ) -- or
dispatcher:removeAllListeners()

dispatcher:printListeners()

All listeners receive the following fields in the parameter event table:

  • event.name (name of the event)
  • event.target (the listener itself)
  • event.source (the dispatcher)

Grab the latest code at Github.

Categories
Corona SDK Lua OOP

EventDispatcher update

Just a quick post that EventDispatcher has been updated with new features including new methods on(), emit(), once() that are similar to Node.js, a new method removeAllListeners(), and a debug function printListeners(). The on() and emit() methods are actually aliases to the addEventListener() and dispatchEvent() methods.

Chris Byerley (aka develephant) who developed Coronium.io and Coronium.gs is using EventDispatcher under the hood for the game server client code. Check out his projects if you’re a Lua / Corona developer.

Here’s the original post for EventDispatcher if you wish to read about it.

Grab the latest code at Github.

Categories
Corona SDK Lua Tips & Tricks

ZeroBrane Studio

For Lua development, whether it is for plain Lua or platforms such as Corona SDK, ZeroBrane Studio is an excellent open-source IDE (written in Lua) for Windows, Mac OS and Linux. I still use Sublime Text with the Corona Editor plugin but ZeroBrane Studio is my first choice for Lua development.

This IDE is updated frequently and has great support from Paul Kulchenko. To grab the latest update before a new version is released, download from the github page, and follow these steps on Mac OS:

  1. Locate ZeroBraneStudio.app in the Applications folder
  2. Right-click on the app and choose Show Package Contents
  3. Open the Contents folder, and then the ZeroBraneStudio folder
  4. Drag and drop everything(*) inside the (github) ZeroBraneStudio folder into the above folder inside the app

* Actually not all files are needed, see an example of files and folders to drag over in the following image:

 

If you have made changes to a theme or configuration (such as tomorrow.lua in the cfg folder), make sure you have a backup copy before replacing everything as described above.

Download the IDE here: http://studio.zerobrane.com

To show Corona SDK reference from right-clicking on a keyword in the editor, add the following code to the end of your user settings (user.lua) found under the Edit | Preferences menu:

showreference = {
	target = 'http://docs.coronalabs.com/api/%s.html',
	transform = function(s)
		local tip = G.GetTipInfo(G.ide:GetEditor(), s)
		if tip then s = tip:match("%)%s*(%S+)") or s end
		s = (G.type(G[s]) == "function" and "global." or "")..s
		s = s..(s:find("[%.%:]") and "" or ".index")
		s = s:find("^_") and "type."..s:sub(2) or "library."..s
		return(s:gsub("[%.%:]","/"))
	end,
}

Add showreference.lua from ZeroBranePackage to the ~/.zbstudio folder if it’s not there already. Quit and relaunch the IDE to see the update.

Categories
Others

DigitalOcean VPS $10 credit

If you’ve been thinking of having your own virtual private server, here’s a referral link to get $10 credit from DigitalOcean. While I won’t be getting any referral credit until $25 has been spent by you, it’s still a good deal to check it out with the two months credit (if you sign up for the $5/month plan).

Categories
Corona SDK Lua OOP

Send custom events with EventDispatcher for Corona SDK / Lua

In Corona SDK, event listeners can only be added to the global Runtime object or to display objects. In order to broadcast messages to event listeners, the event dispatcher is limited to either one or the other. This limitation places messaging in the two scopes instead of between objects that are supposed to be talking to each other. I’ve seen many examples with display objects that are created solely for the purpose of dispatching events. This just doesn’t feel right to me; so I’m releasing my EventDispatcher, perhaps other developers may find it useful too.

Those who came from the good old Flash 5 days may remember FLEM (FLash Event Model). It was the first listener event model for Flash and ActionScript, and was created by Branden Hall and further developed and maintained by me. I’ve adapted the basic event model mechanism found in ActionScript 2/3 to Lua. This EventDispatcher has a similar interface as the listener model in Corona SDK, with some extra features thrown in (such as optional extra parameters when dispatching events, and returning status).

EventDispatcher provides custom event broadcaster/listener mechanism to regular Lua objects, it works as regular Lua 5.1 / 5.2 code, in Corona SDK, and likely other Lua-based frameworks.

[ Update: See http://swfoo.com/?p=718 ]

Basic usage:

    local EvtD = require "EventDispatcher"

    local listener = {
        eventName = function(event)
            print(event.name)
        end
    }

    local broadcaster = EvtD()

    broadcaster:addEventListener( "eventName", listener )
    broadcaster:hasEventListener( "eventName", listener )
    broadcaster:dispatchEvent( { name="eventName" } )
    broadcaster:removeEventListener( "eventName", listener )

Sample code below demonstrates how it can be used:

local EvtD = require "EventDispatcher"

---------------------------------------------------------------------------

-- shared function for cowboys; shows the use of event.target
local function cowboyDraw(event, ...)
	if event.subject then
		print(event.target.name .." is ".. event.name .."ing a gun and shooting a ".. event.subject)
	else
		print(event.target.name .." is ".. event.name .."ing a gun")
	end
end

---------------------------------------------------------------------------

-- table listeners

local cowboy1 = {
	name = "Cowboy1",
	draw = cowboyDraw
}

local cowboy2 = {
	name = "Cowboy2",
	draw = cowboyDraw
}

---------------------------------------------------------------------------

-- listener as table; shows the use of event.source
local iPad = {
	turnOn = function(event, ...)
		print("iPad is turned on by ".. event.source.name .." (table)")
	end,

	turnOff = function(event, ...)
		print("iPad is turned off by ".. event.source.name .." (table)")
	end
}

-- listener as function
local function turnOniPad(event, ...)
	print("iPad is turned on by ".. event.source.name .." (function)")
end

---------------------------------------------------------------------------

-- basic artist draw function
local function artistDraw(event, ...)
	print(event.target.name .." is ".. event.name .."ing a picture")
end

---------------------------------------------------------------------------

-- artist1 is both a listener and a event dispatcher
local artist1 = EvtD{
	name = "Artist1",
	draw = artistDraw,

	-- responds to the 'rest' message, and sends a message to the iPad
	rest = function(event, ...)
		print(event.target.name .." is ".. event.name .."ing")

		-- event.target is artist1
		event.target:dispatchEvent( { name="turnOff" } )
	end
}

-- artist1 tells iPad to listen to the 'turnOff' message
artist1:addEventListener( "turnOff", iPad)

---------------------------------------------------------------------------

-- artist2 is both a listener and a event dispatcher
local artist2 = EvtD{
	name = "Artist2",

	draw = function(event, ...)
		-- event.target is artist2
		event.target:dispatchEvent( { name="turnOn" } )

		if event.subject then
			print(event.target.name .." is ".. event.name .."ing a ".. event.subject .." on the iPad")

			-- shows the use of extra arguments
			local func,pieces,name = ...
			func(pieces,name)
		else
			print(event.target.name .." is ".. event.name .."ing on the iPad")
		end
	end,

	rest = function(event, ...)
		event.target:dispatchEvent( { name="turnOff" } )
		print(event.target.name .." is ".. event.name .."ing")
	end
}

-- shows the use of table and function listeners
artist2:addEventListener( "turnOff", iPad)
artist2:addEventListener( "turnOn", turnOniPad)

---------------------------------------------------------------------------

-- mayor is a event dispatcher who tells others what to do
local mayor = EvtD()

-- mayor shows how much gold is collected
mayor.collectGold = function(nPieces, fromName)
	print("Mayor collected ".. nPieces .." pieces of gold from ".. fromName)
end

-- mayor tells these four people to pay attention to different messages
mayor:addEventListener( "draw", cowboy1 )
mayor:addEventListener( "draw", cowboy2 )
mayor:addEventListener( "draw", artist1 )
mayor:addEventListener( "draw", artist2 )
mayor:addEventListener( "rest", artist2 )

-- mayor sends the 'rest' message
mayor:dispatchEvent( { name="rest" } )
print("Rested 1")

-- mayor tells everyone to draw
mayor:dispatchEvent( { name="draw" } )

-- mayor tells these people to stop listening to the 'draw' message
mayor:removeEventListener( "draw", cowboy1 )
mayor:removeEventListener( "draw", artist1 )
print("Removed")

-- mayor tells artist1 to listen to the 'rest' message
mayor:addEventListener( "rest", artist1 )

-- mayor tells whoever is still listening to rest
mayor:dispatchEvent( { name="rest" } )
print("Rested 2")

-- mayor tells whoever is still listening to draw, with a subject and extra parameters
mayor:dispatchEvent( { name="draw", subject="bandit" }, mayor.collectGold, 42, "Dave" )

Here is the output from the code:

iPad is turned off by Artist2 (table)
Artist2 is resting
Rested 1
Cowboy1 is drawing a gun
Cowboy2 is drawing a gun
Artist1 is drawing a picture
iPad is turned on by Artist2 (function)
Artist2 is drawing on the iPad
Removed
iPad is turned off by Artist2 (table)
Artist2 is resting
Artist1 is resting
iPad is turned off by Artist1 (table)
Rested 2
Cowboy2 is drawing a gun and shooting a bandit
iPad is turned on by Artist2 (function)
Artist2 is drawing a bandit on the iPad
Mayor collected 42 pieces of gold from Dave

And here is the EventDispatcher module:

Update (Sept 12, 2014): Added aliases ‘on’ and ’emit’ for ‘addEventListener’ and ‘dispatchEvent’ for Coronium GS.


-- EventDispatcher.lua
--
-- Provides custom event broadcaster/listener mechanism to regular Lua objects.
--
-- Created by: Dave Yang / Quantumwave Interactive Inc.
--
-- http://qwmobile.com  |  http://swfoo.com/?p=632
--
-- Version: 1.1.4
--
-- Basic usage:
--		local EvtD = require "EventDispatcher"
--		local listener = {
--			eventName = function(event)
--				print(event.name)
--			end
--		}
--		local broadcaster = EvtD()
--		broadcaster:addEventListener( "eventName", listener ) or broadcaster:on( "eventName", listener )
--		broadcaster:hasEventListener( "eventName", listener )
--		broadcaster:dispatchEvent( { name="eventName" } ) or broadcaster:emit( { name="eventName" } )
--		broadcaster:removeEventListener( "eventName", listener )
---------------------------------------------------------------------------

local EventDispatcher = {}

function EventDispatcher:init(o)
	local o = o or {}
	o._listeners = {}
	self.__index = self
	return setmetatable(o, self)
end

---------------------------------------------------------------------------

-- Check if the event dispatcher has registered listener for the event eventName
-- Return boolean (true/false), and if found also return the index of listener object
function EventDispatcher:hasEventListener(eventName, listener)
	if eventName==nil or #eventName==0 or listener==nil then return false end

	local a = self._listeners
	if a==nil then return false end

	for i,o in next,a do
		if o~=nil and o.evt==eventName and o.obj==listener then
			return true, i
		end
	end
	return false
end

---------------------------------------------------------------------------

-- Add a listener for event eventName (a string).
-- Return addition status (true/false), position of listener is also returned if false; position=0 if failed
function EventDispatcher:addEventListener(eventName, listener)
	local found,pos = self:hasEventListener(eventName, listener)
	if found then return false,pos end

	local a = self._listeners
	if a==nil then return false,0 end

	a[#a+1] = { evt=eventName, obj=listener }
	return true
end

-- 'on' is an alias of 'addEventListener'
EventDispatcher.on = EventDispatcher.addEventListener

---------------------------------------------------------------------------

-- Dispatch event (a table, must have a 'name' key), with optional extra parameters.
-- Return dispatched status (true/false).
function EventDispatcher:dispatchEvent(event, ...)
	if event==nil or event.name==nil or type(event.name)~="string" or #event.name==0 then return false end

	local a = self._listeners
	if a==nil then return false end

	local dispatched = false
	for i,o in next,a do
		if o~=nil and o.obj~=nil and o.evt==event.name then
			event.target = o.obj
			event.source = self

			if type(o.obj)=="function" then
				o.obj(event, ...)
				dispatched = true
			elseif type(o.obj)=="table" then
				local f = o.obj[event.name]
				if f~= nil then
					f(event, ...)
					dispatched = true
				end
			end
		end
	end
	return dispatched
end

-- 'emit' is an alias of 'dispatchEvent'
EventDispatcher.emit = EventDispatcher.dispatchEvent

---------------------------------------------------------------------------

-- Remove listener with eventName event from the event dispatcher.
-- Return removal status (true/false).
function EventDispatcher:removeEventListener(eventName, listener)
	local found,pos = self:hasEventListener(eventName, listener)
	if found then
		table.remove(self._listeners, pos)
	end
	return found
end

---------------------------------------------------------------------------

-- create syntactic sugar to automatically call init()
setmetatable(EventDispatcher, { __call = function(_, ...) return EventDispatcher:init(...) end })

return EventDispatcher

EventDispatcher provides a broadcaster/listener event mechanism to regular Lua objects. Corona developers can write cleaner object-oriented messaging code that doesn’t rely on display objects or send messages from the global Runtime.

For the latest code, check out EventDispatcher at github.

Categories
Corona SDK Lua

Lua table remove by key

Lua has a table.remove() function that deletes an element from a table at the specified position, or the last element by default. However, it doesn’t work when the table is an associative array (e.g. {name=”swfoo”, domain=”swfoo.com”} ).

Below is a simple function that deletes a key-value pair from a table. One important feature to note is that instead of modifying the original table, it returns a new table.


-- Remove key k (and its value) from table t. Return a new (modified) table.
function table.removeKey(t, k)
	local i = 0
	local keys, values = {},{}
	for k,v in pairs(t) do
		i = i + 1
		keys[i] = k
		values[i] = v
	end

	while i>0 do
		if keys[i] == k then
			table.remove(keys, i)
			table.remove(values, i)
			break
		end
		i = i - 1
	end

	local a = {}
	for i = 1,#keys do
		a[keys[i]] = values[i]
	end

	return a
end

local t = {name="swfoo", domain="swfoo.com"}
t = table.removeKey(t, "domain")
Categories
Corona SDK iPhone

A mighty PNG

This innocent-looking PNG image makes a huge difference to iOS apps if you need to target retina display devices. At 640×1136 and named “Default-568h@2x.png”, this default launch image tells the app to run in full retina resolution on devices such as iPhone 5. What’s different with this image is the tiny file size of only 184 bytes. You’re welcome to grab it and use it.

Default-568h@2x.png

Categories
Corona SDK

Corona SDK Graphics 2.0 RGB Conversion

Update: A newer version that converts from and to between Graphics 1.0 and 2.0 can be found here.

Here is a simple tool I created to convert the old RGB values (from 0 to 255) to the Graphics 2.0 RGB values (0 to 1):

Enter RGB color values (0-255) separated by commas (e.g. 0, 128, 255):

Categories
Others

Embed Getty Images for free

Getty Images announced their images can now be embedded for free!

Here’s an image of Hong Kong as an example:

Categories
Events

FITC Toronto 2013

fitc13logo
It’s that time of the year again, FITC Toronto 2013 kicks off in less than a week. Get your tickets here.