Handy Code Snippets

I was banging my head against the wall trying to figure out how to use sqlite prepared statements, and I finally got it. Hopefully this small example will save someone some time.

-- insert a new item into a specific set and return the id of the new item function createSetItem(theSetID,theSetItem) local stmt = db:prepare([[INSERT INTO setItems (setID,item) VALUES (:pSetID, :pItem)]]) stmt:bind\_names({pSetID = theSetID, pItem = theSetItem}) stmt:step() local newID = db:last\_insert\_rowid() print("newID: ", newID) return newID end [import]uid: 207504 topic_id: 19231 reply_id: 142637[/import]

I was banging my head against the wall trying to figure out how to use sqlite prepared statements, and I finally got it. Hopefully this small example will save someone some time.

-- insert a new item into a specific set and return the id of the new item function createSetItem(theSetID,theSetItem) local stmt = db:prepare([[INSERT INTO setItems (setID,item) VALUES (:pSetID, :pItem)]]) stmt:bind\_names({pSetID = theSetID, pItem = theSetItem}) stmt:step() local newID = db:last\_insert\_rowid() print("newID: ", newID) return newID end [import]uid: 207504 topic_id: 19231 reply_id: 142637[/import]

just in case you didn’t notice, the comma adds a tab (or large space) between the first text and the following text. So, it’s not the same as a concatenation … of two strings.

Perhaps there if you used tostring(yourbool) it would concatenate your bool and string into a string.

print("Value of my bool = " … tostring(myBool))

[import]uid: 99429 topic_id: 19231 reply_id: 144725[/import]

just in case you didn’t notice, the comma adds a tab (or large space) between the first text and the following text. So, it’s not the same as a concatenation … of two strings.

Perhaps there if you used tostring(yourbool) it would concatenate your bool and string into a string.

print("Value of my bool = " … tostring(myBool))

[import]uid: 99429 topic_id: 19231 reply_id: 144725[/import]

just in case you didn’t notice, the comma adds a tab (or large space) between the first text and the following text. So, it’s not the same as a concatenation … of two strings.

Perhaps there if you used tostring(yourbool) it would concatenate your bool and string into a string.

print("Value of my bool = " … tostring(myBool))

[import]uid: 99429 topic_id: 19231 reply_id: 144725[/import]

just in case you didn’t notice, the comma adds a tab (or large space) between the first text and the following text. So, it’s not the same as a concatenation … of two strings.

Perhaps there if you used tostring(yourbool) it would concatenate your bool and string into a string.

print("Value of my bool = " … tostring(myBool))

[import]uid: 99429 topic_id: 19231 reply_id: 144725[/import]

I like this thread.  Here are some of the favorites I’ve made, and some I’ve found and used:

either gives you a random result from a selection of choices without having to do an if math.random() then A else B line of code.

Usage: local computerPlayerName = either( “John”, “Frank”, “Bob”, “Melissa”, “Joan” )

local function either( ... ) if #arg == 0 then return nil else return arg[math.random( #arg )] end end

Multiple rotations of an object got your head spinning like crazy? Turn it into a clean angle of 0-359 using the modulo operator before doing any rotations on it:

local cleanAngle = player.rotation % 360 player.rotation = cleanAngle

angleBetweenPoints gets you, well, the angle between two points:

local function angleBetweenPoints( sX, sY, dX, dY ) local angleBetween local xDist, yDist = dX - sX, dY - sY if xDist == 0 then print( "Divide by zero!" ) angleBetween = 0 else angleBetween = math.deg( math.atan( yDist / xDist ) ) if ( sX \< dX ) then angleBetween = angleBetween + 90 else angleBetween = angleBetween - 90 end if angleBetween == 0 then angleBetween = -180 elseif angleBetween == -180 then angleBetween = 0 end end return angleBetween end

freeSpot finds a free spot for your display objects in a table.

Usage: enemy[freespot( enemy )] = display.newImageRect( “enemy1.png”, 64, 64 )

local function freeSpot( table ) local spot, i local max = table.maxn( table ) for i = 1, max do if spot == nil and object[i].x == nil then spot = i end end if spot == nil then spot = table.maxn( table ) + 1 print( "No free spot within table, adding to the end, #" .. spot ) else print( "Using free spot #" .. spot ) end return spot end

clamped quickly sets a low and high range for a given variable:

Usage: energy = clamped( energy + bonus, 0, 100 )

local function clamped( value, lowest, highest ) return math.max( lowest, math.min( highest, value ) ) end

I like this thread.  Here are some of the favorites I’ve made, and some I’ve found and used:

either gives you a random result from a selection of choices without having to do an if math.random() then A else B line of code.

Usage: local computerPlayerName = either( “John”, “Frank”, “Bob”, “Melissa”, “Joan” )

local function either( ... ) if #arg == 0 then return nil else return arg[math.random( #arg )] end end

Multiple rotations of an object got your head spinning like crazy? Turn it into a clean angle of 0-359 using the modulo operator before doing any rotations on it:

local cleanAngle = player.rotation % 360 player.rotation = cleanAngle

angleBetweenPoints gets you, well, the angle between two points:

local function angleBetweenPoints( sX, sY, dX, dY ) local angleBetween local xDist, yDist = dX - sX, dY - sY if xDist == 0 then print( "Divide by zero!" ) angleBetween = 0 else angleBetween = math.deg( math.atan( yDist / xDist ) ) if ( sX \< dX ) then angleBetween = angleBetween + 90 else angleBetween = angleBetween - 90 end if angleBetween == 0 then angleBetween = -180 elseif angleBetween == -180 then angleBetween = 0 end end return angleBetween end

freeSpot finds a free spot for your display objects in a table.

Usage: enemy[freespot( enemy )] = display.newImageRect( “enemy1.png”, 64, 64 )

local function freeSpot( table ) local spot, i local max = table.maxn( table ) for i = 1, max do if spot == nil and object[i].x == nil then spot = i end end if spot == nil then spot = table.maxn( table ) + 1 print( "No free spot within table, adding to the end, #" .. spot ) else print( "Using free spot #" .. spot ) end return spot end

clamped quickly sets a low and high range for a given variable:

Usage: energy = clamped( energy + bonus, 0, 100 )

local function clamped( value, lowest, highest ) return math.max( lowest, math.min( highest, value ) ) end

Very nice page

I tried to implement “Printing memory usage to the terminal”
I put the function between createScene and enterScene
I tried to call: printMemUsage() but that din´t work

Tested this:

local showMem = function()
print( collectgarbage( “count” ) / 1000 , “MB” )
end
local memTimer = timer.performWithDelay( 1000, showMem, 1 )

–[[ Now you have a handler you can use when removing the timer
and if you like to run it every second to see how mem is building up
just change the last param to 0
You could also put the results into a table and find the max and min of mem usage I guess
… this one works nice in storyboard for me
just put it in enterScene func :slight_smile:
–]]

Very nice page

I tried to implement “Printing memory usage to the terminal”
I put the function between createScene and enterScene
I tried to call: printMemUsage() but that din´t work

Tested this:

local showMem = function()
print( collectgarbage( “count” ) / 1000 , “MB” )
end
local memTimer = timer.performWithDelay( 1000, showMem, 1 )

–[[ Now you have a handler you can use when removing the timer
and if you like to run it every second to see how mem is building up
just change the last param to 0
You could also put the results into a table and find the max and min of mem usage I guess
… this one works nice in storyboard for me
just put it in enterScene func :slight_smile:
–]]

alternative for string.len

text = “hello corona”

print(string.len(text)

print(#text)

alternative for string.len

text = “hello corona”

print(string.len(text)

print(#text)

I needed a HSL and HSV converter to RGB, so i dig here and there, made my own optimisations and here is the shortest i’ve managed to get: (mostly inspired by TinyPenguin but with some fixes and shortcuts)

HSL to RGB:

-- input h-0-360(deg.), s-0-100(%), l-0-100(%) local function hsl(h, s, l) if s == 0 then return l\*.01,l\*.01,l\*.01 end local c, h = (1-math.abs(2\*(l\*.01)-1))\*(s\*.01), (h%360)/60 local x, m = (1-math.abs(h%2-1))\*c, ((l\*.01)-.5\*c) c = ({{c,x,0},{x,c,0},{0,c,x},{0,x,c},{x,0,c},{c,0,x}})[math.ceil(h)] or {c,x,0} return (c[1]+m),(c[2]+m),(c[3]+m) end

HSV to RGB:

-- input h-0-360(deg.), s-0-100(%), v-0-100(%) local function hsv(h,s,v) if s == 0 then return v\*.01,v\*.01,v\*.01 end local c, h = ((s\*.01)\*(v\*.01)), (h%360)/60 local x, m = c\*(1-math.abs(h%2-1)), (v\*.01)-c c = ({{c,x,0},{x,c,0},{0,c,x},{0,x,c},{x,0,c},{c,0,x}})[math.ceil(h)] or {c,x,0} return (c[1]+m),(c[2]+m),(c[3]+m) end

I needed a HSL and HSV converter to RGB, so i dig here and there, made my own optimisations and here is the shortest i’ve managed to get: (mostly inspired by TinyPenguin but with some fixes and shortcuts)

HSL to RGB:

-- input h-0-360(deg.), s-0-100(%), l-0-100(%) local function hsl(h, s, l) if s == 0 then return l\*.01,l\*.01,l\*.01 end local c, h = (1-math.abs(2\*(l\*.01)-1))\*(s\*.01), (h%360)/60 local x, m = (1-math.abs(h%2-1))\*c, ((l\*.01)-.5\*c) c = ({{c,x,0},{x,c,0},{0,c,x},{0,x,c},{x,0,c},{c,0,x}})[math.ceil(h)] or {c,x,0} return (c[1]+m),(c[2]+m),(c[3]+m) end

HSV to RGB:

-- input h-0-360(deg.), s-0-100(%), v-0-100(%) local function hsv(h,s,v) if s == 0 then return v\*.01,v\*.01,v\*.01 end local c, h = ((s\*.01)\*(v\*.01)), (h%360)/60 local x, m = c\*(1-math.abs(h%2-1)), (v\*.01)-c c = ({{c,x,0},{x,c,0},{0,c,x},{0,x,c},{x,0,c},{c,0,x}})[math.ceil(h)] or {c,x,0} return (c[1]+m),(c[2]+m),(c[3]+m) end

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 &nbsp;&nbsp;&nbsp;&nbsp;timer.cancel(checkTime) &nbsp;&nbsp;&nbsp;&nbsp;hasInternet = false print("NO INTERNET") else &nbsp;&nbsp;&nbsp;&nbsp;timer.cancel(checkTime) &nbsp;&nbsp;&nbsp;&nbsp;print("event.response = " .. event.response) &nbsp;&nbsp;&nbsp;&nbsp;print("time to live = " .. netTime .. "seconds") &nbsp;&nbsp;&nbsp;&nbsp;print("HAS INTERNET") &nbsp;&nbsp;&nbsp;&nbsp;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) &nbsp;

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