Re: Small Useful Functions
Posted: Wed May 28, 2014 9:28 am
It also might not add them in the order you want to -- if you want the values from the other table added in order, use ipairs.
Code: Select all
requirei = local function(d, ...)
args = {...}
for k, i in ipairs(args) do
file = d .. i
require(file)
end
end
Code: Select all
local function requirei(d, ...)
for i, v in ipairs{...} do
require(d .. v)
end
end
Code: Select all
local function clear(t)
for i,_ in ipairs(t) do
table.remove(t, i)
end
end
Code: Select all
local function clear(t)
for i = #t, 1, -1 do
t[i] = nil
end
end
Code: Select all
local function RemoveHole( Table ) -- Removes nils from tables.
local New = {}
for Index, Value in pairs( Table ) do
New[Index] = Value
end
return New
end
If you remove all of the entries, then you don't even need to traverse the table backwards. This works, too:Robin wrote:Better would be:Code: Select all
local function clear(t) for i = #t, 1, -1 do t[i] = nil end end
Code: Select all
local function clear(t)
for i = 1,#t do
t[i] = nil
end
end
What exactly should this function do? What do you mean by "remove nils values?" A variable with value "nil" does not exist. So if you have a nil-value in a table then the key-value pair does not exist. Assigning nil to a variable is a way to delete variable.davisdude wrote:Hopefully there's nothing wrong with this one (just to keep Robin's job a little easier )Code: Select all
- snip -
Code: Select all
function newAr(h,w)
local ar = {}
for i=1,h do
ar[i] = {}
for j=1,w do
ar[i][j] = 0
end
end
return ar
end
Code: Select all
function transpose(ar)
local ar2 = newAr(#ar,#ar[1])
for i=1,#ar do
for j=1,#ar[i] do
ar2[j][i] = ar[i][j]
end
end
return ar2
end
Code: Select all
function vFlip(ar)
local ar2 = newAr(#ar,#ar[1])
for i=1,#ar do
for j=1,#ar[i] do
ar2[#ar - i + 1][j] = ar[i][j]
end
end
return ar2
end
function hFlip(ar)
local ar2 = newAr(#ar,#ar[1])
for i=1,#ar do
for j=1,#ar[i] do
ar2[i][#ar[i]-j + 1] = ar[i][j]
end
end
return ar2
end
Code: Select all
function rotLeft(ar)
return vFlip(transpose(ar))
end
function rotRight(ar)
return hFlip(transpose(ar))
end