loq_util

Utility functions used by other modules.

Usage

require(“loq_util”)

Summary
loq_utilUtility functions used by other modules.
Debugging
atracePrints a debugging message with a time stamp and stack trace.
formatMSFormat milliseconds into a string HH:MM:SS:MS
functionInfoReturns the file and line numbers for a function’s definition
loq_declareUsed to declare global values.
loq_undeclaredChecks if a string name of a variable has been declared as a global.
xinspectReturns a nicely formated string with the properties and contents listed of the parameter passed in.
String
string:splitSplits the string using with a separator
Table
table.indexOfSearches a table for an item and returns its index or nil if not found
table.copyReturns a shallow copy of array, i.e.
table.removeItemSearches a table for an item and removes it if present.
Math
rotateVec2Rotates vector components x, y through an angle.
Events
loq_listenersUses adds event dispatching to the object.
Graphics Optimization
loq_displayAdds functions to the display object to optimize transformations: translating, rotating, scaling.
Modules
unrequireRemoves a required lua file from the loaded packages to free up application memory.
Examples
Examples
Using atrace and xinspect for debuggingUsing atrace and xinspect for debugging.
Global declaration of variables before usageGlobal declaration of variables before usage.
Unloading modules from application memory with unrequire.Unloading modules from application memory with unrequire.
Using loq_display to boost performance of transforming display objectsBased on testing as of build 721, accessing the properties of a display object in Corona is very slow.

Debugging

atrace

function atrace(_msg,
_depth)

Prints a debugging message with a time stamp and stack trace.

Parameters

  • _msg The message to display, can be a string, function, or table
  • _depth The depth of the stack.  Defaults to 1.

formatMS

function formatMS(_ms)

Format milliseconds into a string HH:MM:SS:MS

Parameters

  • _ms Milliseconds from a call like system.getTimer()

Returns

A string in the format HH:MM:SS:MS where HH is hours, MM is minutes, SS is seconds, and MS is milliseconds

functionInfo

function functionInfo(_func)

Returns the file and line numbers for a function’s definition

Parameters

  • _func The function

Returns

A string with the file and line numbers for the function’s definition.  If not a valid function then returns nil.

loq_declare

function loq_declare (_name,
_initval)

Used to declare global values.  If loq_DeclareGlobals is true before the loq_util module is loaded, then global values used without loq_declare() throw an error.  From kam187 on the Corona Code Exchange

Parameters

  • _name Name of the global variable.
  • _initval Initial value of the variable.

Usage

local loq_DeclareGlobals = true
require('loq_util')
loq_declare("MyGlobal", {})

loq_undeclared

function loq_undeclared(_name)

Checks if a string name of a variable has been declared as a global.

Parameters

  • _name Name of the global variable.

Returns

  • true if the variable name is undeclared with loq_declare.
  • false if the variable has been declared with loq_declare.

xinspect

function xinspect(_t)

Returns a nicely formated string with the properties and contents listed of the parameter passed in.

Parameters

  • _t A value.

Returns

A nicely formated string with the properties and contents listed.

Usage

local values = { a = 1, b = 'hello' }
atrace(xinspect(values))

String

string:split

function string:split(sSeparator,
nMax,
bRegexp)

Splits the string using with a separator

Parameters

  • sSeparator A string separator.

Returns

A table of strings.

Table

table.indexOf

function table.indexOf(_t,
_item)

Searches a table for an item and returns its index or nil if not found

Parameters

  • _t The table.
  • _item The item to find.

Returns

The index or nil if not found.

NOTE: This is only defined if table.indexOf does not already exist in the runtime environment.  It is added only for compatibility with older versions of the Corona SDK.

table.copy

function table.copy(...)

Returns a shallow copy of array, i.e. the portion of the array (table) with integer keys.  A variable number of additional arrays can be passed in as optional arguments.  If an array has a hole (a nil entry), copying in a given source array stops at the last consecutive item prior to the hole.

Parameters

  • ...  Optional, one or more tables.

Returns

Returns a shallow copy of combined arrays.

NOTE: This is only defined if table.copy does not already exist in the runtime environment.  It is added only for compatibility with older versions of the Corona SDK.

table.removeItem

function table.removeItem(_t,
_item)

Searches a table for an item and removes it if present.

Parameters

  • _t The table.
  • _item The item to remove.

Math

rotateVec2

function rotateVec2(_degrees,
_x,
_y)

Rotates vector components x, y through an angle.

Parameters

  • _degrees The angle in degrees
  • _x X component of 2D vector
  • _y Y component of 2D vector

Returns

The rotated x and y values.

Events

loq_listeners

function loq_listeners(_obj)

Uses adds event dispatching to the object.  Can be used to replace the event dispatching functions (addEventListener, removeEventListener, dispatchEvent) for display objects or to add event dispatching to regular objects.  Also adds clearListeners for remove all event listeners or event listeners of a certain type.

Parameters

  • _obj A table.

NOTE: loq_listeners is used in SpriteGroups to replace the Corona display object event dispatching system in order to prevent misbehavior in the Corona event dispatching API.

Graphics Optimization

loq_display

function loq_display(_d)

Adds functions to the display object to optimize transformations: translating, rotating, scaling.  Use the methods translateTo, rotateTo and scaleTo to transform the display object, instead of directly setting the x, y, rotation, xScale, and yScale values for higher performance.

The speed up is due to caching the x, y, etc properties and using the translate, rotate, and scale functions to operate on these cached values.

The loq_display function also modifies translate, rotate, and scale to used cached values.

You can directly access the cached values as cx, cy, crotation, cxScale, and cyScale.

Methods

  • translateTo Takes x and y target values to position the object.
  • scaleTo Takes xScale and yScale target values to scale the object.
  • rotateTo Takes an rotation target value to rotate the object.
  • cache Initialize the display object and its cache properties.  Optionally takes x, y, rotation, xScale, yScale.

Cached Properties

  • cx Cached x value
  • cy Cached y value
  • crotation Cached rotation value
  • cxScale Cached xScale value
  • cyScale Cached yScale value

You can use the cached properties for increased performance.

Note: You should use the actual x, y, and rotation properties if the display object is a physics body.

Check out the example below.

Parameters

  • _d A display object

Modules

unrequire

function unrequire(m)

Removes a required lua file from the loaded packages to free up application memory.

Parameters

  • _filename The name of a lua file to be removed from the loaded packages to clear up application memory.

Examples

Summary
Examples
Using atrace and xinspect for debuggingUsing atrace and xinspect for debugging.
Global declaration of variables before usageGlobal declaration of variables before usage.
Unloading modules from application memory with unrequire.Unloading modules from application memory with unrequire.
Using loq_display to boost performance of transforming display objectsBased on testing as of build 721, accessing the properties of a display object in Corona is very slow.

Examples

Using atrace and xinspect for debugging

Using atrace and xinspect for debugging.  You might use print to get debugging info from the Corona terminal.  You can use atrace where you would use print to get extra information like line numbers, timings, and a stack trace.

atrace can check if the value passed in is a function or a table and attempt to print it out.  You can use xinspect on tables and functionInfo on functions if you need to concatenate their values to a string.

require('loq_util')

-- print out a message
atrace('This works like print, but you get a time, file, line number, and function')

-- print out a value
local myvar = 10
atrace(myvar)

local mytable = {a = 100}
atrace(mytable) -- that's better!

--atrace('mytable ' .. mytable) -- Throws an error.  Can't convert a table to a string

-- Use xinspect on mytable
atrace('mytable ' .. xinspect(mytable)) -- that's better


local function myfunc()
    atrace('inside a function')

    local function anotherfunc()
        atrace("notice that atrace prints the function you're in!")
        atrace("let's print the stack 2 deep", 2)

        local function funcInFunc()
            atrace("let's print the stack 2 deep again", 2)
            atrace('now all the way', 10)
        end

        funcInFunc()

        atrace('assigning the function to a variable in lua we lose the original name')
        local renameMyFunc = funcInFunc
        renameMyFunc()

        atrace("we can get some info about the function renameMyFunc points to")
        atrace(renameMyFunc)
    end

    anotherfunc()
end

myfunc()

Global declaration of variables before usage

Global declaration of variables before usage.

If you want to force declarations of globals before usage set a variable loq_DeclareGlobals to true before requiring ‘loq_util’.  Then you can use the loq_declare declare the global variable before using it.  You can also use loq_undeclared to check whether a variable has been declare before accessing it.

NOTE: With loq_DeclareGlobals enabled, some Corona modules you require must be declared first because they create globals (e.g.  ‘physics’, ‘sprite’)

main.lua -- using loq_DeclareGlobals in main.lua sets the option for you application

loq_DeclareGlobals = true -- if nil or false then globals don't require declarations
require('loq_util')

loq_declare('physics')
require('physics') -- The Corona physics module must be declared because it creates a global.

loq_declare('myglobal')
myglobal = 10

atrace(loq_undeclared('myUndeclaredGlobal'))

atrace(myUndeclaredGlobal) -- throws an error

yourmodule.lua -- Using the module function creates a global value.  You need to declare the module if loq_DeclareGlobals is true.

if loq_DeclareGlobals then
    loq_declare('yourmodule')
end

module(..., package.seeall) -- this globally defines your module when required
--  the rest of the module

Unloading modules from application memory with unrequire.

Unloading modules from application memory with unrequire.  Loading a module with the standard ‘require’ function creates a global variable.  And loads the module into global memory.  If you’re temporarily using a module, then this is basically a form of a memory leak.

You can reclaim some of the application memory by calling ‘unrequire’ on the required module.  Try commmenting and uncommenting your require and unrequire calls with the loq_profiler to see the difference in your application memory usage.

require('loq_util')
-- instantiate to keep an eye on application memory
require('loq_profiler').createProfiler()

local myModule = require('myModule')
-- ... some processing here, don't need the module anymore
unrequire('myModule') -- removes the module from the global packages and reclaims some app memory

Using loq_display to boost performance of transforming display objects

Based on testing as of build 721, accessing the properties of a display object in Corona is very slow.  http://developer.anscamobile.com/forum/2011/12/03/tips-optimization-101#comment-71273

Using the loq_display function on display objects is a workaround to speed up the performance of transforming display objects.  By default, Spriteloq SpriteGroups use loq_display.

With loq_display applied to a display object it gets these new methods and properties which can be used in place of accessing the x, y, rotation, xScale, yScale for transforms.

Methods

  • translateTo Takes x and y target values to position the object.
  • scaleTo Takes xScale and yScale target values to scale the object.
  • rotateTo Takes an rotation target value to rotate the object.
  • cache Initialize the display object and its cache properties.  Optionally takes x, y, rotation, xScale, yScale.

Cached Properties

  • cx Cached x value
  • cy Cached y value
  • crotation Cached rotation value
  • cxScale Cached xScale value
  • cyScale Cached yScale value

You can use the cached properties for increased performance.

Note: You should use the actual x, y, and rotation properties if the display object is a physics body.

require('loq_util')

local rect = display.newRect(0, 0, 100, 100)
loq_display(rect)  -- gains performance transform methods and properties and caches the initial values

rect:cache(200, 200, 45) -- sets the initial cached properties

local angle = 45

local x = 200
local y = 200

local function enterFrame(_e)
    -- accessing the x, y, rotation, xScale and yScale properties is slower
    rect:rotateTo(angle)
    angle = angle + 1

    rect:translateTo(x, y)
    x = x + 1

    -- this access is fast
    local cx = rect.cx

    -- this access is slow, but if rect is a physics body you must use x
    cx = rect.x
end

Runtime:addEventListener('enterFrame', enterFrame)
function atrace(_msg,
_depth)
Prints a debugging message with a time stamp and stack trace.
function formatMS(_ms)
Format milliseconds into a string HH:MM:SS:MS
function functionInfo(_func)
Returns the file and line numbers for a function’s definition
function loq_declare (_name,
_initval)
Used to declare global values.
function loq_undeclared(_name)
Checks if a string name of a variable has been declared as a global.
function xinspect(_t)
Returns a nicely formated string with the properties and contents listed of the parameter passed in.
function string:split(sSeparator,
nMax,
bRegexp)
Splits the string using with a separator
function table.indexOf(_t,
_item)
Searches a table for an item and returns its index or nil if not found
function table.copy(...)
Returns a shallow copy of array, i.e.
function table.removeItem(_t,
_item)
Searches a table for an item and removes it if present.
function rotateVec2(_degrees,
_x,
_y)
Rotates vector components x, y through an angle.
function loq_listeners(_obj)
Uses adds event dispatching to the object.
function loq_display(_d)
Adds functions to the display object to optimize transformations: translating, rotating, scaling.
function unrequire(m)
Removes a required lua file from the loaded packages to free up application memory.
Close