Skip to content

Instantly share code, notes, and snippets.

@nagolove
Last active February 2, 2020 15:28
Show Gist options
  • Save nagolove/590aa9e05eee654c8dee6fc33feea103 to your computer and use it in GitHub Desktop.
Save nagolove/590aa9e05eee654c8dee6fc33feea103 to your computer and use it in GitHub Desktop.
Some lua snippets for common tasks.
-- pattern from https://stackoverflow.com/questions/5243179/what-is-the-neatest-way-to-split-out-a-path-name-into-its-components-in-lua/12191225#12191225
local path, fname, extension = string.match(arg[2], "(.-)([^\\/]-%.?([^%.\\/]*))$")
-- использование __СПЕЦ_ИМЕН__ глобальных переменных, как условий.
if not __ONCE__ then
local f = lg.getFont()
if f then print(string.format("current font size = %d", f:getHeight())) end
__ONCE__ = true
end
-- Re: Functions with a variable number of arguments
-- url - https://stackoverflow.com/a/32146853
function print2(...)
-- best, for this situation:
print(...)
-- or:
local args = {...}
print(unpack(args))
-- or, a more robust version of the above because it deals with nils properly, just like the first example:
local nargs = select("#", ...)
local args = {}
for i = 1, nargs do
args[i] = tostring((select(i, ...)))
end
print(table.concat(args, "\t"))
end
-- чему соответствует данный паттерн?
-- источник https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
local x = tonumber(xyz[1]:match("^%s*(.-)%s*$"))
-- [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
--[[
16Tomatons said, on Ноябрь 15, 2016 at 10:13 пп
Функция next в нехешированных массивах работает исключительно медленно.
Есть способ это исправить, добавив какой-либо символьный ключ, но это не нужно, ибо обход в обратном порядке эффективнее.
Сам когда-то давно с таким морочился, доходил самостоятельно.
Очень удивила лаконичность решения.
P.S. Локальную переменную value (которая равна t[i]) желательно объявлять вне тела цикла, обновляя в цикле, иначе плодится слишком много локальных переменных, которые тут же выбрасываются.
--]]
local t = {1, 3, 4, 9}
do
local value
for i = #t, 1, -1 do
value = t[i]
if value > 2 and value < 9 then
table.remove(t, i)
end
end
end
--Или вообще итератор:
function ripairs(t)
local i = #t + 1
return function()
i = i - 1
if t[i] then return i, t[i] end
end
end
local t = {1, 2, 3, 4, 5}
for i, v in ripairs(t) do
if v%2 == 0 then table.remove(t, i) end
end
-- ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
-- hackerrank.com trick for make print writing to debug output.
-- use fptr handle for challengle task output
local fptr = io.open(os.getenv("OUTPUT_PATH"), "w")
-- from http://comments.gmane.org/gmane.comp.lang.lua.luajit/910
-- c-like integer division
function cdiv(a, b)
local q = a / b
return (q > 0) and math.floor(q) or math.ceil(q)
end
-- Prints elemets of set whick keys ~= nil
function printSet(set)
local tmp = {}
for _, v in pairs(set) do
tmp[#tmp + 1] = v
end
print(table.concat(tmp, ","))
end
-- TODO Add other functions, like:
-- filter,
-- reduce
function map(t, func, ...)
local tmp = {}
for k, v in pairs(t) do
tmp[k] = func(k, v)
end
return tmp
end
-- FIXME Not tested!
function reverse(t, func)
local arr = {}
local body = function() end
if func then
body = function()
arr[#arr + 1] = func(t[i])
end
else
body = function()
arr[#arr + 1] = func(t[i])
end
end
for i = #arr, 1, -1 do
body()
end
return arr
end
-- http://lua-users.org/wiki/LuaStyleGuide
-- clone a small table t (warning: this has a system dependent limit on table size; it was just over 2000 on one system):
u = {unpack(t)}
-- https://github.com/Yonaba/30log
-- class library
local class = require '30log'
local Window = class("Window")
local appWindow = Window:new()
local appWindow = Window()
-- constructor
function Window:init(p)
self.p = p
end
function Window.__tostring(w)
return string.format("window %s", w.name)
end
-- mixin
local Geometry = {
getSize = function(self)
return self.w, self.h
end
}
Window:include(Geometry)
-- inheritance
local FrameBuffer = Window:extend("Window")
local fb = FrameBuffer:new()
--[[
When you type
whatever = require "whatever"
Lua tries to find a package named whatever in many places, mostly having whatever somewhere in their names. If none of these is found, Lua gives an error message listing them all, something like
stdin:1: module 'whatever' not found:
no field package.preload['whatever']
no file '/usr/local/share/lua/5.2/whatever.lua'
no file '/usr/local/share/lua/5.2/whatever/init.lua'
no file '/usr/local/lib/lua/5.2/whatever.lua'
no file '/usr/local/lib/lua/5.2/whatever/init.lua'
no file './whatever.lua'
no file '/usr/local/lib/lua/5.2/whatever.so'
no file '/usr/local/lib/lua/5.2/loadall.so'
no file './whatever.so'
stack traceback:
[C]: in function 'require'
stdin:1: in main chunk
[C]: in ?
A schematic representation of that list is kept in the variable package.path. For the above list, that variable contains
/usr/local/share/lua/5.2/?.lua;/usr/local/share/lua/5.2/?/init.lua;/usr/local/lib/lua/5.2/?.lua;/usr/local/lib/lua/5.2/?/init.lua;./?.lua
--]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment