PtokaX forum

Archive => Archived 5.1 boards => Finished Scripts => Topic started by: st0ne-db on 04 November, 2006, 20:51:46

Title: PtokaX Common Script Functions Module
Post by: st0ne-db on 04 November, 2006, 20:51:46
I thought that since PPK made is so easy to load modules in PX 0.3.5.2 that I would
compile some useful code bits into a module.  ;D
just save the script as pxcom.lua inside PtokaX\libs or PtokaX\scripts\libs


-------------------------------------------------------------------------------------
-- PtokaX Common Script Functions Module (Compiled by St0ne_db)
--
-- These code bits where compiled from these two thread:
-- http://forum.ptokax.org/index.php?topic=6419.0  -- Lua 5.1 Code Bits
-- http://forum.ptokax.org/index.php?topic=2332.0  -- Scripting:Utilities:Central
--
-- Init Module:
--  Lua 5.1  :  pxcom = require "pxcom"
--
--  Lua 5.0.X:  require "compat-51"
--              pxcom = require "pxcom"
--              pxcom.Compat();
--
-- Usage:
--  All functions are referenced through the module name.
--  ie.
--      local curTime = pxcom.GetTime()
--
-------------------------------------------------------------------------------------
module ("pxcom")

--Compatibility with Lua 5.0.X
Compat = function()
table.maxn = table.getn or table.maxn
math.fmod = math.mod or math.fmod
string.gmatch = string.gfind or string.gmatch
end

--Herodes
SplitTagDescr = function(str)
local tag, descr, tTab = "", "", {}
--- get those letters in the tTab
for i= 1, string.len(str) do
tTab[i] = string.sub(str, i,i)
end
--- move backwards until we find a "<"
local i = table.maxn(tTab)
repeat
tag = tTab[i]..tag
i = i - 1
until tTab[i] == "<"
--- add the missing "<"
tag = "<"..tag
--- construct the description
for l = 1, i-1 do
descr = descr..tTab[l]
end
return descr, tag
end

--Herodes
--strftime("%ddays %dhours %dminutes %dseconds", 90061)
StrfTime = function(form, time)
local d, h, m
d, time = math.floor(time/86400), math.fmod(time, 86400)
h, time = math.floor(time/3600), math.fmod(time, 3600)
m, time = math.floor(time/60), math.fmod(time, 60)
return string.format(form, d, h, m, time)
end

--Typhoon
--DoTime(os.clock())
DoTimeUnits = function(time)
local time = time*1000
local msg = ""
local tO = {
[1] = { 86400000, 0, "days"},
[2] = { 3600000, 0, "hours"},
[3] = { 60000, 0, "minutes"},
[4] = { 1000, 0, "seconds"},
};
for i , v in (tO) do
if time >= tO[i][1] then
repeat
tO[i][2] = tO[i][2] + 1
time = time - tO[i][1]
until time < tO[i][1]
end
end
for i,v in tO do
if tO[i][2] ~= 0 then
msg = msg.." "..tO[i][2].." "..tO[i][3]
end
end
return msg
end

--Herodes
LineStr = function(str)
local out = ""
local c = nil
for i = 1, string.len(str) do
if c == nil then
c = 1
else c = c +1
end
out = out..string.gsub(string.sub(str, c, c), "(.)",  "( "..string.sub(str, c, c).." )", 1)
end
str = out
out = nil
return str
end

--NotRabidWombat
GetByteUnit = function(intSize)
local tUnits = { "Bytes", "KB", "MB", "GB", "TB" }
intSize = tonumber(intSize);
local sUnits;
for index = 1, tablr.maxn(tUnits) do
if(intSize < 1024) then
sUnits = tUnits[index];
break;
else
intSize = intSize / 1024;
end
end
return string.format("%0.2f %s",intSize, sUnits);
end

--VidFamne
--(Modified Julian "minute" number. This restricts the algorithm to 1900 Mar 01 until 2100 Feb 28)
Jmn = function()
local D = tonumber(os.date("%d"))
local H = tonumber(os.date("%H"))
local minutE = tonumber(os.date("%M"))
local Y = tonumber(os.date("%Y"))
local M = tonumber(os.date("%m"))
if M <= 2 then
M = M + 12
Y=Y-1
end
mn = 1440*(math.floor(Y*365,25) + math.floor((M+1)*30,6) + D -428) + H*60 + minutE
return mn
end

--Mutor
--// Profile Counter
cProfile = function(what)
local disp = ""
local table,online,offline = GetUsersByProfile(what),0,0
for i, User in table do
if GetItemByName(User) then
online = online + 1
else
offline = offline + 1
end
end
disp = disp.."Online: "..online.."\tOffline: "..offline
return disp
end

--kepp
--// Get amount of Online users by Profile Name
pOnline = function(strProfile)
   tblFolks = GetUsersByProfile(strProfile)
   Count = 0
   for i=0,table.maxn(tblFolks) do
      if GetItemByName(tblFolks[i]) then
         Count = Count + 1
      end
   end
   return Count
end

--dragos_sto
GetTime = function()
local Time = os.date("%H")..":"..os.date("%M")
return Time
end

--dragos_sto
GetDate = function()
local Date = os.date("%d").." - "..os.date("%B").." - "..os.date("%Y")
return Date
end

--Herodes
--Find info from tag ( DC++ )
FindMode = function(user)
local _,_,mode = string.find(user.sMyInfoString,  ",M:(%S)")
modestr = "Mode : "..mode
return modestr
end

--Herodes
--Find info from tag ( DC++ )
FindHubs = function(user)
local _,_,guest,regged,opped = string.find(user.sMyInfoString,  ",H:(%d+)/(%d+)/(%d+)")
gueststr = guest.." as normal user"
regstr = regged.."as registered user"
opstr = opped.." as operator"
allstr = "Hubs : "..guest.." ( normal ), "..regged.." ( registered ), "..opped.." ( operator )"
guestnum = tonumber(guest)
regnum = tonumber(regged)
opnum = tonumber(opped)
allnum = tonumber(guest) + tonumber(regged) + tonumber(opped)
return gueststr, regstr, opstr, allstr, guestnum, regnum, opnum, allnum
end

--Herodes
--Find info from tag ( DC++ )
FindSlots = function(user)
local _,_,slots = string.find(user.sMyInfoString,  ",S:(%d+)")
slotstr = "Slots :\t"..slots
slotnum = tonumber(slots)
return slotstr, slotnum
end

--Mutor
--Seperate thousands with comma,returns a string by sam_lie
--Where 'number' is number to format
CommaSeperator = function(number)
local int = number
while true do
int, x = string.gsub(int, "^(-?%d+)(%d%d%d)", '%1,%2')
if (x==0) then
break
end
end
return int
end

--Mutor
--Returns UTC timezone as a string by Mutor
TimeZone = function()
local h,m = math.modf((os.time()-os.time(os.date"!*t"))/ 3600)
return string.format("%+d UTC",(h + (60 * m)))
end

--Mutor
--Check for file, returns string and filesize by Mutor
--Usage: local f,s = FileSpecs("Path/filename.ext")
FileSpecs = function(pathfile)
local size = 0
local file,error = io.open(pathfile, "rb")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
file:close()
pathfile = pathfile.." does exist. "
else
pathfile = string.sub(error,1,-2)
end
if size < 1024 then
        size = string.format("%.2f Bytes",size)
else
size = string.format("%.2f Kb.",(size/1024))
end
return pathfile,"Filesize: "..size
end

-- Serialize by nErBoS
SaveToFile = function(file , table , tablename)
local handle = io.open(file,"w+")
handle:write(pxcom.Serialize(table, tablename))
handle:flush()
handle:close()
end

-- Serialize by nErBoS
LoadFromFile = function(filename)
local f = io.open(filename)
if f then
local r = f:read("*a")
f:flush()
f:close()
local func,err = loadstring(r)
if func then x,err = pcall(func) end
end
end

-- Serialize by nErBoS
Serialize = function(tTable, sTableName, sTab)
assert(tTable, "tTable equals nil");
assert(sTableName, "sTableName equals nil");
assert(type(tTable) == "table", "tTable must be a table!");
assert(type(sTableName) == "string", "sTableName must be a string!");
sTab = sTab or "";
sTmp = ""
sTmp = sTmp..sTab..sTableName.." = {\n"
for key, value in pairs(tTable) do
local sKey = (type(key) == "string") and string.format("[%q]",key) or string.format("[%d]",key);
if(type(value) == "table") then
sTmp = sTmp..pxcom.Serialize(value, sKey, sTab.."\t");
else
local sValue = (type(value) == "string") and string.format("%q",value) or tostring(value);
sTmp = sTmp..sTab.."\t"..sKey.." = "..sValue
end
sTmp = sTmp..",\n"
end
sTmp = sTmp..sTab.."}"
return sTmp
end

--bastya_elvtars
--- use it like : cmd = string.match( string.sub( data, 1, -2 ) ,"%b<>%s+"..GetHubPrefixes().."(%S+)")
-- command prefix use prefix hubs
GetHubPrefixes = function()
local s = ''
for i, pref in pairs(frmHub:GetPrefixes()) do
s = s.."%"..pref
end
return '['..s..']'
end

--Mutor
--Merge two tables      by plop
Add2Tables = function(tTable1, tTable2)
local tTable = tTable2
for a,b in pairs(tTable1) do
tTable[a] = b
end
return tTable
end

--Mutor
--Random Pawword [passcode] generator
PassCode = function(int)
local gc,no = nil,table.getn
if _VERSION == "Lua 5.1" then
gc,no = "collect",table.maxn
end
local t = {{48,57},{65,90},{97,122}} -- ASCII range(s)
local msg = ""
for i=1, int do
local r = math.random(1,no(t))
msg = msg..string.char(math.random(t[r][1],t[r][2]))
end
return msg
end

--St0ne_db
doLoadFile = function(xFile)
local xStr = "";
local hxFile,sErr = io.open(tVar.sFolder.."/"..xFile,"r");
if hxFile then
xStr = hxFile:read("*a");
hxFile:close(xFile);
io.flush();
return xStr;
else
return nil;
end
end

--St0ne_db
doSaveFile = function(xFile,xStr,xMode)
if not xMode then xMode = "w" end
local hxFile,sErr = io.open(tVar.sFolder.."/"..xFile,xMode);
if hxFile then
hxFile:write(xStr);
hxFile:close(xFile);
io.flush();
return 1;
else
return nil;
end
end
Title: Re: PtokaX Common Script Functions Module
Post by: Herodes on 04 November, 2006, 21:09:19
Thats a good effort to start with,... why don't we take this to the wiki?
Title: Re: PtokaX Common Script Functions Module
Post by: piraya on 08 November, 2006, 15:22:37
Quotejust save the script as pxcom.lua inside PtokaX\libs or PtokaX\scripts\libs

I dont have thet libs folder ???  do i have to create it?
Title: Re: PtokaX Common Script Functions Module
Post by: amenay on 21 December, 2006, 10:04:17
Shouldn't there be definitions of what modules or libraries (in this case the standard Lua libs) which are required for the module,  or am I doing this wrong?  To get it to work I either had to use:

module("pxcom", package.seeall)

or this:

local pxcom = ("pxcom")
local base = _G
local io = require("io")
local string = require("string")
local math = require("math")
module ("pxcom")


With the second method it's a bit more of a pain because you have to go through each function in the basic library and make sure it is defined as being in the "base." table which normally would be global.  This kind of brings me to my next question;  am I saving any overhead using the second method over the first?  Sorry if I'm unclear with any of this, I think this module is a really good idea. Saying that, I'm also curious what everyone else's experience with it has been.  I attached the second method below just in the case that anyone wants to try it out.  Hopefully I didn't miss anything.

Edit: Forgot to add that declaring pxcom this way no longer necessitates the need for you to specify module.function when calling another function within the module, as seen above with Serialize.

//ame
Title: Re: PtokaX Common Script Functions Module
Post by: bastya_elvtars on 21 December, 2006, 10:59:50
In the second method, you are better off doing this: module("pxcom",package.seeall)
Title: Re: PtokaX Common Script Functions Module
Post by: amenay on 21 December, 2006, 11:30:59
For any particular reasons? It's obviously cleaner and easier, but is it quicker?  (this is purely out of curiosity and future reference, nothing I'm using at this point would be extensive enough to notice a difference in speed) Also this is what I was referring to as the first method. So in that case it wouldn't be "in the second method" if you catch my drift. ;)