Skip to content

Instantly share code, notes, and snippets.

@Aadv1k
Last active February 17, 2022 04:59
Show Gist options
  • Save Aadv1k/ce5638068b3533bea4d26afc092287ab to your computer and use it in GitHub Desktop.
Save Aadv1k/ce5638068b3533bea4d26afc092287ab to your computer and use it in GitHub Desktop.
A simple utils file for lua inspired by JavaScript and some other helpful functions
------------------------------------------------------------------
-- NAME: utils.lua
-- AUTHOR: Aadvik<[email protected]>
-- DESCRIPTION: A simple utils file.
-- LICENCE: GNU Public license
------------------------------------------------------------------
function table.indexOf(tab, elem)
for i,v in pairs(tab) do
if v == elem then
return i
end
end
return nil
end
function table.lastIndexOf(tab, elem)
for count=#tab,1,-1 do
if tab[count] == elem then
return count
end
end
return nil
end
function table.reverse(tab)
local result = {}
for count=#tab,1,-1 do
table.insert(result, tab[count])
end
return result
end
-- is this how filter works?
function table.filter(tab, target)
local result = {}
for _,item in pairs(tab) do
if target(item) then
table.insert(result, target(item))
end
end
return result
end
-- A monolithic "Just works" Implementation.
function table.stringify(tab)
local s = ''
for count=1,#tab do
if count+1 > #tab then
if type(tab[count]) == 'string' then
s = s.."\""..tab[count].."\""
elseif type(tab[count]) == 'boolean' then
s = s..tostring(tab[count])
elseif type(tab[count]) == 'table' then
s = s..table.stringify(tab[count])
else
s = s..tab[count]
end
break
elseif type(tab[count]) == 'string' then
s = s.."\""..tab[count].."\", "
elseif type(tab[count]) == 'boolean' then
s = s..tostring(tab[count])..", "
elseif type(tab[count]) == 'table' then
s = s..table.stringify(tab[count])..', '
else
s = s..tab[count]..', '
end
end
return '{ '..s..' }'
end
function table.print(tab) print(table.stringify(tab)) end
function string.matrix(inp)
local result = {}
for lines in inp:gmatch('[^\r\n]+') do
local line = {}
for count=1,#lines do
table.insert(line, lines:sub(count, count))
end
table.insert(result, line)
end
return result
end
function ternary(cond, m1, m2)
if cond then
return m1
end
return m2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment