This is a post that lists some handy code snippets. They will generally be small examples and the list will be added to in time and also if you guys post some snippets I will add them to this list.
Print/Display a boolean value preceded by a string
Problem :
If you try to simply print a boolean value preceded by a string like so :
local myBool = true
print("Value of my bool = " … myBool)[/lua]
You will get the following error :
“attempt to concatenate field ‘myBool’ (a boolean value)”
To get around this you instead use a comma.
–Usage
local myBool = true
print("Value of my bool = ", myBool)[/lua]
This will output :
Value of my bool = true
Iterating through a key/pair table in order
As you know if you iterate through a key/pair table, it does not do so in the order it was defined.
Eg:
local myTable = { ["key1"] = 1, ["key2"] = 2, ["key3"] = 3, } for k, v in pairs(myTable) do print(myTable[k]) end
will print :
1, 3, 2
Sometimes that is fine, but it is not always what you want.
To iterate in order you can use the following function (taken from the lua wiki)
local myTable = { ["key1"] = 1, ["key2"] = 2, ["key3"] = 3, } local function \_\_genOrderedIndex( t ) local orderedIndex = {} for key in pairs(t) do table.insert( orderedIndex, key ) end table.sort( orderedIndex ) return orderedIndex end local function orderedNext(t, state) -- Equivalent of the next function, but returns the keys in the alphabetic -- order. We use a temporary ordered key table that is stored in the -- table being iterated. --print("orderedNext: state = "..tostring(state) ) if state == nil then -- the first time, generate the index t.\_\_orderedIndex = \_\_genOrderedIndex( t ) key = t.\_\_orderedIndex[1] return key, t[key] end -- fetch the next value key = nil for i = 1,table.getn(t.\_\_orderedIndex) do if t.\_\_orderedIndex[i] == state then key = t.\_\_orderedIndex[i+1] end end if key then return key, t[key] end -- no more value to return, cleanup t.\_\_orderedIndex = nil return end --This is the function you will use to replace "pairs" local function orderedPairs(t) -- Equivalent of the pairs() function on tables. Allows to iterate -- in order return orderedNext, t, nil end for k, v in orderedPairs(myTable) do print(myTable[k]) end
That will print:
1, 2, 3
Shuffling a table
Say you are making a card game and want to shuffle your table containing your cards. Here is one function that can do it.
local function shuffle(t) local rand = math.random assert(t, "table.shuffle() expected a table, got nil") local iterations = #t local j for i = iterations, 2, -1 do j = rand(i) t[i], t[j] = t[j], t[i] end end --Usage shuffle(myTable)
Checking if a file exists
This speaks for itself, to check if a file exists you can use a handy function like this:
local function doesFileExist(theFile, path) local thePath = path or system.DocumentsDirectory local filePath = system.pathForFile(theFile, thePath) local results = false local file = io.open(filePath, "r") --If the file exists, return true if file then io.close(file) results = true end return results end --Usage doesFileExist("levels.data") --Returns true/false --Or doesFileExist("levels.data", system.ResourceDirectory) --Returns true/false
Get distance between two objects
This is a commonly needed function, it simply returns the distance between two objects
local function getDistanceBetween(obj1, obj2) return math.ceil(math.sqrt( ((obj2.y - obj1.y) \* (obj2.y - obj1.y)) + ((obj2.x - obj1.x) \* (obj2.x - obj1.x)) )) end --Usage local plane = display.newRect(100, 100, 40, 40) local bird = display.newRect(200, 100, 40, 40) getDistanceBetween(plane, bird) --In this case it will return 100
Printing memory usage to the terminal
A lot of people ask how do i monitor my memory usage? Here is a handy function that will print it neatly to the terminal and format it so it is easy to understand.
local function printMemUsage() local memUsed = (collectGarbage("count")) / 1000 local texUsed = system.getInfo( "textureMemoryUsed" ) / 1000000 print("\n---------MEMORY USAGE INFORMATION---------") print("System Memory Used:", string.format("%.03f", memUsed), "Mb") print("Texture Memory Used:", string.format("%.03f", texUsed), "Mb") print("------------------------------------------\n") return true end --Usage printMemUsage() --Best to call when you are finished changing scenes once
[import]uid: 84637 topic_id: 19231 reply_id: 319231[/import]