Handy Code Snippets

Thought I’d share this as it might be usual for others.

I needed to detect if I had a good internet connection to prevent my app from hanging when requesting ads on a poor connection.  The existing methods only seemed to work if you had a good connection or no connection, so I came up with the below.  The code could probably be optimised.

hasInternet = false function networkListener( event ) if ( event.isError ) then     timer.cancel(checkTime)     hasInternet = false print("NO INTERNET") else     timer.cancel(checkTime)     print("event.response = " .. event.response)     print("time to live = " .. netTime .. "seconds")     print("HAS INTERNET")     hasInternet = true end end params = {} params.timeout = 3 netTime = 0 function netTimer() netTime = netTime + .1 end checkTime = timer.performWithDelay(100,netTimer,0) checkNet = network.request( "http://www.xxxxxxx.com/check.php", "POST", networkListener,params)  

The network request will connect to a php file on my web server, if the server responds within the timeout period, the hasInternet variable is set to true.  If it fails to connect or times out the hasInternet variable is left as false.  The timer function is for testing purposes so you can work out what to set the timeout to.  An acceptable internet connection usually responds in less than 3 seconds, generally 3G is around .75-2

the php code is

\<?php echo "ok"; ?\> &nbsp;

I call this on launch, and on a loading screen between games.  I can then use the hasInternet variable to see if I can launch ad’s etc without hanging the app.

@gazjm, this is great! Thank you very much for sharing. 

Need screen captures for a particular device that you don’t have?

Taken from http://forums.coronalabs.com/topic/45148-screenshots-for-app-store-submission.  Thanks, ksan!

-- hit 'c' to capture your screen local function cap(event) if event.keyName== "c" and event.phase == "up" then local screenCap = display.captureScreen( true ) display.remove (screenCap) screenCap = nil end return true end Runtime:addEventListener("key",cap) -- hit 'c' to capture your screen

Thanks for that but all credit goes to @roboward (since he contributed the code) and @jstrahan (since he contributed the idea). I just tweaked it a little. 

Not a snippet but a library. inspect.lua from https://github.com/kikito/inspect.lua . Extremely useful. 

This function transform any Lua table into a human-readable representation of that table.

The objective here is human understanding (i.e. for debugging), not serialization or compactness.

Iterating through a table in a sorted manner.
The pairs function iterates over a table, but the problem is the order in which it iterates is not definite.
This is a custom function spairs (sorted pairs), which does exactly that

 

local function spairs(t, order) &nbsp; &nbsp; -- collect the keys &nbsp; &nbsp; local keys = {} &nbsp; &nbsp; for k in pairs(t) do keys[#keys+1] = k end &nbsp; &nbsp; -- if order function given, sort by it by passing the table and keys a, b, &nbsp; &nbsp; -- otherwise just sort the keys&nbsp; &nbsp; &nbsp; if order then &nbsp; &nbsp; &nbsp; &nbsp; table.sort(keys, function(a,b) return order(a, b) end) &nbsp; &nbsp; else &nbsp; &nbsp; &nbsp; &nbsp; table.sort(keys) &nbsp; &nbsp; end &nbsp; &nbsp; -- return the iterator function &nbsp; &nbsp; local i = 0 &nbsp; &nbsp; return function() &nbsp; &nbsp; &nbsp; &nbsp; i = i + 1 &nbsp; &nbsp; &nbsp; &nbsp; if keys[i] then &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return keys[i], t[keys[i]] &nbsp; &nbsp; &nbsp; &nbsp; end &nbsp; &nbsp; end end &nbsp;

So the Usage would be… 
 

local t = { a = 1, b = 2, c = 3 } local function&nbsp; sortKeysFunction(key1,key2) &nbsp; &nbsp; return key1\<key2 end&nbsp; for k,v in spairs(t,sortKeysFunction) do&nbsp; &nbsp; &nbsp;print(k,v) end &nbsp;

So the above implementation of spairs function always iterates over the table in the alphabetical order of its keys
The key1<key2 code in the sortKeysFunction function sors the keys in alphabetic order

The result will always be 

a   1 

b   2

c   3

Source : http://stackoverflow.com/questions/15706270/sort-a-table-in-lua

Calculating the bearing between two GPS points

function Geo_Angle( lat1, lon1, lat2, lon2)

– More info here http://simon.fearby.com/blog/

  local dLon = math.rad(lon2-lon1);

  local y = math.sin(dLon) * math.cos(math.rad(lat2));

  local x = math.cos(math.rad(lat1)) * math.sin(math.rad(lat2)) - math.sin(math.rad(lat1)) * math.cos(math.rad(lat2)) * math.cos(dLon);

  local brng = math.deg(math.atan2(y, x));

  return ((brng + 360) % 360);

end

My Lua code to convert raw accelerometer data to degrees for an Augmented Reality @CoronaLabs mobile/tablet project http://simon.fearby.com/blog/?p=2134

           local xAxisData = --insert xaxis sensor data here

            local yAxisData = --insert yaxis sensor data here

            local zAxisData = --insert zaxis sensor data here

            --Convert raw 0.0 ~ 1.0 sensor datad to degrees.

            local xAngle = math.atan(tonumber(xAxisData) / (math.sqrt((tonumber(yAxisData) * tonumber(yAxisData))) + (tonumber(zAxisData) * tonumber(zAxisData))))

            local yAngle = math.atan(tonumber(yAxisData) / (math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) +  (tonumber(zAxisData) * tonumber(zAxisData)))))

            local zAngle = math.atan(math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) + (tonumber(yAxisData) * tonumber(yAxisData))) / tonumber(zAxisData));

            xAngle = xAngle * 180.00

            yAngle = yAngle * 180.00

            zAngle = zAngle * 180.00

            xAngle = xAngle / 3.141592

            yAngle = yAngle / 3.141592

            zAngle = zAngle / 3.141592

            --Round down a bit and display

            print("X Degrees: " … tostring( math.round(xAngle,1)) … " (Original X: " … tonumber(wwsettings.xgravitylast) … “)”)

            print("Y Degrees: " … tostring( math.round(yAngle,1)) … " (Original Y: " … tonumber(wwsettings.ygravitylast) … “)”)

            print("Z Degrees: " … tostring( math.round(zAngle,1)) … " (Original Z: " … tonumber(wwsettings.zgravitylast) … “)”)

Can you add these to the code exchange if you are not already?  http://code.coronalabs.com/

Thanks

Rob

Done ( http://code.coronalabs.com/code/simple-accelerometer-data-conversion-degrees ), My first Git.

Calculating the bearing between two GPS points

function Geo_Angle( lat1, lon1, lat2, lon2)

– More info here http://simon.fearby.com/blog/

  local dLon = math.rad(lon2-lon1);

  local y = math.sin(dLon) * math.cos(math.rad(lat2));

  local x = math.cos(math.rad(lat1)) * math.sin(math.rad(lat2)) - math.sin(math.rad(lat1)) * math.cos(math.rad(lat2)) * math.cos(dLon);

  local brng = math.deg(math.atan2(y, x));

  return ((brng + 360) % 360);

end

My Lua code to convert raw accelerometer data to degrees for an Augmented Reality @CoronaLabs mobile/tablet project http://simon.fearby.com/blog/?p=2134

           local xAxisData = --insert xaxis sensor data here

            local yAxisData = --insert yaxis sensor data here

            local zAxisData = --insert zaxis sensor data here

            --Convert raw 0.0 ~ 1.0 sensor datad to degrees.

            local xAngle = math.atan(tonumber(xAxisData) / (math.sqrt((tonumber(yAxisData) * tonumber(yAxisData))) + (tonumber(zAxisData) * tonumber(zAxisData))))

            local yAngle = math.atan(tonumber(yAxisData) / (math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) +  (tonumber(zAxisData) * tonumber(zAxisData)))))

            local zAngle = math.atan(math.sqrt((tonumber(xAxisData) * tonumber(xAxisData)) + (tonumber(yAxisData) * tonumber(yAxisData))) / tonumber(zAxisData));

            xAngle = xAngle * 180.00

            yAngle = yAngle * 180.00

            zAngle = zAngle * 180.00

            xAngle = xAngle / 3.141592

            yAngle = yAngle / 3.141592

            zAngle = zAngle / 3.141592

            --Round down a bit and display

            print("X Degrees: " … tostring( math.round(xAngle,1)) … " (Original X: " … tonumber(wwsettings.xgravitylast) … “)”)

            print("Y Degrees: " … tostring( math.round(yAngle,1)) … " (Original Y: " … tonumber(wwsettings.ygravitylast) … “)”)

            print("Z Degrees: " … tostring( math.round(zAngle,1)) … " (Original Z: " … tonumber(wwsettings.zgravitylast) … “)”)

Can you add these to the code exchange if you are not already?  http://code.coronalabs.com/

Thanks

Rob

Done ( http://code.coronalabs.com/code/simple-accelerometer-data-conversion-degrees ), My first Git.