Hey ppl ...
I just want to see how many Utility snippets we can gather before reapeting ourselves ...:D
By saying that I mean :
Code snippets that can be used as they are to return some specific result ....
Lets kick off with some basic ones :
------------------------------------------------------ -? System ?- ------------------------------------------------------
--- // --- Getting data for the truely Global Variables ...
------------------------------------------------------------------------------------------------------------------------------
function GetTime() --- The Time
seconds = date("%S")
minutes = date("%M")
hours = date("%H")
time = hours..":"..minutes..":"..seconds
return time
end
------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------
function GetDate() --- The Date
day = date("%d")
month = date("%m")
year = date("%y")
date = day.."-"..month.."/"..year
return date
end
------------------------------------------------------------------------------------------------------------------------------
Some user-based stuff goes here
------------------------------------------------------ - User Object - ------------------------------------------------------
--- // --- User Info standard .. :D (these go into DataArrival ..)
------------------------------------------------------------------------------------------------------------------------------
function FindMode(user) ---- Find info from tag ( DC++ )
s,e,mode = strfind(user.sMyInfoString, ",M:(%S)")
modestr = "Mode : "..mode
return modestr
end
------------------------------------------------------------------------------------------------------------------------------
function FindHubs(user) ---- Find info from tag ( DC++ )
s,e,guest,regged,opped = strfind(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
------------------------------------------------------------------------------------------------------------------------------
function FindSlots(user) ---- Find info from tag ( DC++ )
s,e,slots = strfind(user.sMyInfoString, ",S:(%d+)")
slotstr = "Slots :\t"..slots
slotnum = tonumber(slots)
return slotstr, slotnum
end
------------------------------------------------------------------------------------------------------------------------------
Carrying on with an external file ...
------------------------------------------------------ - File Operation - ------------------------------------------------------
--- // --- This is so info can be saved in a file ( retrieval method has to be posted as well )
------------------------------------------------------------------------------------------------------------------------------
function Serialize(tTable, sTableName, hFile, sTab) --- Famous Utility Function
assert(tTable, "tTable equals nil");
assert(sTableName, "sTableName equals nil");
assert(hFile, "hFile equals nil");
assert(type(tTable) == "table", "tTable must be a table!");
assert(type(sTableName) == "string", "sTableName must be a string!");
sTab = sTab or "";
write(hFile, sTab..sTableName.." = {\n" );
for key, value in tTable do
local sKey = ( type(key) == "string" ) and format("[%q]",key) or format("[%d]",key);
if ( type(value) == "table" ) then
Serialize(value, sKey, hFile, sTab.."\t");
else local sValue = (type(value) == "string") and format("%q",value) or tostring(value);
write(hFile, sTab.."\t"..sKey.." = "..sValue);
end
write(hFile, ",\n");
end
write(hFile, sTab.."}");
end
-----------------------------------------------------------------------------------
function SaveFile(table , tablename, file)
local hFile = openfile(file, "w");
Serialize(table, tablename, hFile);
closefile(hFile);
end
-----------------------------------------------------------------------------------
function LoadFile(file)
assert(readfrom(file),file.." is not found.")
dostring(read("*all"))
readfrom()
end
------------------------------------------------------------------------------------------------------------------------------
Pls try to keep the functions as indepented as possible ...
This aims to save time from ppl staring their own scripts and ppl trying to understand
how you do stuff in the awsome Ptx scirpting platform.
Feel free and share all ..
--// Get amount of Online users by Profile Name
function Online(strProfile)
tblFolks = GetUsersByProfile(strProfile)
Count = 0
for i=0,getn(tblFolks) do
if GetItemByName(tblFolks[i]) then
Count = Count + 1
end
end
return Count
end
thanks for the input kepp,
I think I can use this straight away :)
"--- Famous Utility Function"
LOL!
On that note: here is a more sophisticated version of serialization:
http://www.dekorte.com/Software/Lua/LuaPickle/Download/Pickle_preLua5.0/Pickle.lua
Binary Search
function BinarySearch(tTable, SearchVar)
assert(tTable and SearchVar);
local iBot, iMid, iTop = 1, nil, getn(tTable);
local CompVal = nil;
if(getn(tTable) == 0) then return -1, 1; end
while(iBot <= iTop) do
iMid = floor((iTop + iBot) / 2);
CompVal = tTable[iMid];
if(CompVal == nil) then return -1, -1; end
if(SearchVar < CompVal) then
iTop = iMid - 1;
elseif(SearchVar > CompVal) then
iBot = iMid + 1;
else
return iMid, -1;
end
end
if(SearchVar > CompVal) then
iMid = iMid + 1;
end
return -1, iMid;
end
Element Count for Zero Based Array
Usefull for GetUsersByProfile(...)
function zgetn(tTable)
return (tTable and (getn(tTable) + (tTable[0] and 1 or 0))) or 0;
end
This is an excellent idea. However, I feel it will grow out of control as the thread grows in size. Perhaps someone should host these snippets on a site, offering a name, a simple description, and a link to the snippet. Personally, I wouldn't expect any credit to be given since most of these functions have been writen before.
*EDIT*
"Pls try to keep the functions as indepented as possible ..."
These functions should probably not modify globals then. Remember, you can return more than one variable.
*/EDIT*
-NotRabidWombat
QuoteOriginally posted by NotRabidWombat
This is an excellent idea. However, I feel it will grow out of control as the thread grows in size. Perhaps someone should host these snippets on a site, offering a name, a simple description, and a link to the snippet. Personally, I wouldn't expect any credit to be given since most of these functions have been writen before.
-NotRabidWombat
sounds like a nice new section for my website.
i'll bombart herodes 2 moderator of that section.
plop
Thanks for putting ur pieces up boys ...
Now this one returns any given text file ...
function ReadTextFile(file)
local message = "\r\n"
readfrom(file, "r")
while 1 do
local line = read()
if ( line == nil ) then break
else message = message.."\t"..line.."\r\n"
end
end
readfrom()
return message
end
function Readtextfile(file)
local text = ""
local line
local handle = openfile(file, "r")
if (handle) then
local line = read(handle)
while line do
if line then
text = text..line.."\r\n"
end
line = read(handle)
end
closefile(handle)
else
text = text.."Error file "..file.." not found!\r\n"
end
return text
end
And here is a other one
--// Get ProfileName
function tProfileName(who)
local tmp = GetProfileName(who.iProfile) or "User"
return tmp
end
This is a nice and small one
Hey Opti nice keystrokes ... :D
--- I was thinking that a zipped file would be nice to have ....
but this utility collection has to grow more ...
I am sure some ppl in this forum have some debugger snippets ... so I'd like to see something like this too ...
Keep em coming !!
This exert is explained here: http://lua-users.org/wiki/OptimisationCodingTips
function fast_assert(condition, ...)
if not condition then
if getn(arg) > 0 then
assert(condition, call(format, arg))
else
assert(condition)
end
end
end
Aother flavor.
function Readtextfile(file)
local text;
local handle = readfrom(file);
if (handle) then
text = gsub( read(handle, "*a") , "\n", "\r\n" ) or
"Empty File.\r\n";
closefile(handle)
else
text = "Error file "..file.." not found!\r\n"
end
return text
end
-- Return: fractional part of number
function frac(num)
return num - floor(num);
end
-- Convert Gregorian Date to Julian Date
function JulianDate(DAY, MONTH, YEAR, HOUR, MINUTE, SECOND) -- HOUR is 24hr format
local jy, ja, jm;
assert(YEAR ~= 0);
assert(YEAR ~= 1582 or MONTH ~= 10 or DAY < 4 or DAY > 15);
--The dates 5 through 14 October, 1582, do not exist in the Gregorian system!");
if(YEAR < 0 ) then
YEAR = YEAR + 1;
end
if( MONTH > 2) then
jy = YEAR;
jm = MONTH + 1;
else
jy = YEAR - 1;
jm = MONTH + 13;
end
local intgr = floor( floor(365.25*jy) + floor(30.6001*jm) + DAY + 1720995 );
--check for switch to Gregorian calendar
local gregcal = 15 + 31*( 10 + 12*1582 );
if(DAY + 31*(MONTH + 12*YEAR) >= gregcal ) then
ja = floor(0.01*jy);
intgr = intgr + 2 - ja + floor(0.25*ja);
end
--correct for half-day offset
local dayfrac = HOUR / 24 - 0.5;
if( dayfrac < 0.0 ) then
dayfrac = dayfrac + 1.0;
intgr = intgr - 1;
end
--now set the fraction of a day
local frac = dayfrac + (MINUTE + SECOND/60.0)/60.0/24.0;
--round to nearest second
local jd0 = (intgr + frac)*100000;
local jd = floor(jd0);
if( jd0 - jd > 0.5 ) then jd = jd + 1 end
return jd/100000;
end
-- Convert Julian Date to Gregorian Date
-- return: day, month, year, hour, minute, second
function GregorianDate(jDate)
local j1, j2, j3, j4, j5;
--
-- get the date from the Julian day number
--
local intgr = floor(jd);
local frac = jd - intgr;
local gregjd = 2299161;
if( intgr >= gregjd ) then --Gregorian calendar correction
local tmp = floor( ( (intgr - 1867216) - 0.25 ) / 36524.25 );
j1 = intgr + 1 + tmp - floor(0.25*tmp);
else
j1 = intgr;
end
--correction for half day offset
local dayfrac = frac + 0.5;
if( dayfrac >= 1.0 ) then
dayfrac = dayfrax - 1.0;
j1 = j1 + 1;
end
j2 = j1 + 1524;
j3 = floor( 6680.0 + ( (j2 - 2439870) - 122.1 )/365.25 );
j4 = floor(j3*365.25);
j5 = floor( (j2 - j4)/30.6001 );
local d = floor(j2 - j4 - floor(j5*30.6001));
local m = floor(j5 - 1);
if( m > 12 ) then m = m - 12 end
local y = floor(j3 - 4715);
if( m > 2 ) then y = y - 1; end
if( y <= 0 ) then y = y - 1; end
--
-- get time of day from day fraction
--
local hr = floor(dayfrac * 24.0);
local mn = floor((dayfrac*24.0 - hr)*60.0);
f = ((dayfrac*24.0 - hr)*60.0 - mn)*60.0;
local sc = floor(f);
f = f - sc;
if( f > 0.5 ) then sc = sc + 1; end
return d,m,y,hr,mn,sc;
end
-NotRabidWombat
Here's another Julian number function. Gives you minute-number. ;)function Jmn() --(Modified Julian "minute" number. This restricts the algorithm to 1900 Mar 01 until 2100 Feb 28)
local D = tonumber(date("%d"))
local H = tonumber(date("%H"))
local minutE = tonumber(date("%M"))
local Y = tonumber(date("%Y"))
local M = tonumber(date("%m"))
if M <= 2 then
M = M + 12
Y=Y-1
end
mn = 1440*(floor(Y*365,25) + floor((M+1)*30,6) + D -428) + H*60 + minutE
return mn
end
Here's another i worked on to Show bots to specific profiles
function Main()
SendToAll(UnregBot("Unregister_My_Old_Bot"))
end
function NewUserConnected(curUser)
-- Show bots depending on what User Profiles are
if curUser.iProfile == 0 or curUser.iProfile == 1 then
curUser:SendData(RegBot("Test"))
end
end
OpConnected = NewUserConnected
--////////////////////////////////////////////////////////////////////////////
--//
--////////////////////////////////////////////////////////////////////////////
function RegBot(...)
strBots = "";
for i,v in arg do
if not strfind(v,getn(arg)) then
strBots = strBots..v.."$$";
end
end
if strBots then return "$OpList "..strBots.."|" end
end
function UnregBot(...)
strBots = "";
for i,v in arg do
if not strfind(v,getn(arg)) then
strBots = strBots.."$Quit "..v.."|";
end
end
if strBots then return strBots; end
end
Back to contribution mode after a dreadful afternoon dealing diplomatics
Here is a nice one ... I don't know about its efficiency(optimal mem usage), though it gets the job done ...
--- // --- Transforming bytes into KB, MB, GB, TB, PT and Returning the ideal (highest possible) Unit
function BytesPostFix(size)
local tUnits = {}
tUnits[1] = tonumber(size)
if ((tonumber(tUnits[1])) and (tonumber(tUnits[1]) >= 1024)) then
tinsert(tUnits, 2, ((tonumber(tUnits[1]))/1024))
else return tonumber(tUnits[1])
end
if ((tonumber(tUnits[2])) and (tonumber(tUnits[2]) >= 1024)) then
tinsert(tUnits, 3, ((tonumber(tUnits[1]))/(1024^2)))
end
if ((tonumber(tUnits[3])) and (tonumber(tUnits[3]) >= 1024)) then
tinsert(tUnits, 4, ((tonumber(tUnits[1]))/(1024^3)))
end
if ((tonumber(tUnits[4]) and (tonumber(tUnits[4]) >= 1024)) then
tinsert(tUnits, 5, ((tonumber(tUnits[1]))/(1024^4)))
end
if ((tonumber(tUnits[5]) and (tonumber(tUnits[5]) >= 1024)) then
tinsert(tUnits, 6, ((tonumber(tUnits[1]))/(1024^5)))
end
local rdSizeStr = format("%0.2f", tUnits[getn(tUnits)])
if (getn(tUnits) == 1) then
rdSizeStr = rdSizeStr.." B"
elseif (getn(tUnits) == 2) then
rdSizeStr = rdSizeStr.." KB"
elseif getn(tUnits) == 3 then
rdSizeStr = rdSizeStr.." MB"
elseif getn(tUnits) == 4 then
rdSizeStr = rdSizeStr.." GB"
elseif getn(tUnits) == 5 then
rdSizeStr = rdSizeStr.." TB"
elseif getn(tUnits) == 6 then
rdSizeStr = rdSizeStr.." PB"
end
tUnits = nil
return rdSizeStr
end
Nice, This does pretty much the same thing though
function GetByteUnit(intSize)
intSize = tonumber(intSize);
strPut = "";
if intSize >= 1073741824 then
strPut = format("%0.2f",intSize / 1024 / 1024 / 1024).." GB"
elseif intSize >= 1048576 then
strPut = format("%0.2f",intSize / 1024 / 1024).." MB"
elseif intSize >= 1024 then
strPut = format("%0.2f",intSize / 1024).." Kb"
else
strPut = intSize.." Bytes"
end
return strPut or "0 Bytes";
end
How small can we go?!
Just add or remove to the end of tUnits depending on your needs.
function GetByteUnit(intSize)
local tUnits = { "Bytes", "KB", "MB", "GB", "TB" }
intSize = tonumber(intSize);
local sUnits;
for index = 1, getn(tUnits) do
if(intSize < 1024) then
sUnits = tUnits[index];
break;
else
intSize = intSize / 1024;
end
end
return format("%0.2f %s",intSize, sUnits);
end
-NotRabidWombat
Ok, Nice, but consider it LUA 4!! lol
Or maybe you did make it by purpose for lua5 ?
Nice :)
Oh duh! Did my testing in Lua 5 :-)
Just forgot to convert.
Edited
-NotRabidWombat
Another way to prove the results of colloaborative work would be for me to grab this b>mb>gb>tb snippet and use it rightaway... :D
Thats what I am gonna do lol
--- thanks for this one to kepp and NotRambitWombat
also a small but very usefull one ...
doGetProfile = GetProfileName(user.iProfile)
usage :
"..doGetProfile.."
-Typhoon?
Say u wanna view a table for debugging purposes, huh?
try the following script ....
tTable = { ["theFirstvalue"] = {
["level"] = "AAA1",
["nrvalues"] = 33300000,
["goodarray"] = { "array A1", "array A2", "array A3", 123 },
},
["theSecond"] = {
["2level"] = "AAA2",
["2nrvalues"] = 3,
["2goodarray"] = { "array B1", "array B2", "array B3", 456},
},
};
function DataArrival(user,data)
if strsub(data, 1, 1) == "<" then
local s, e, cmd = strfind(data, "%b<>%s+(%S+)")
SendToAll(cmd)
if strsub(cmd, 1 ,3) == "!do" then
ShowTable(tTable)
end
end
end
function ShowTable(table)
if count == nil then
count = 1
else
count = count + 1
end
for index, val in table do
if type(val) == "table" then
SendToAll("--------> Table/Array STARTS here ...")
ShowTable(val)
SendToAll("<-------- Table/Array ENDS here ...")
elseif type(val) == "string" or type(val) == "number" then
if count ~= nil then
SendToAll(strrep("- ", count*2).."> "..index.." >?< "..val.." it is a "..type(val))
else
SendToAll( "> "..index.." >?< "..val.." it is a "..type(val))
end
end
end
end
the function u need is this one ...
function ShowTable(table)
if count == nil then
count = 1
else
count = count + 1
end
for index, val in table do
if type(val) == "table" then
SendToAll("--------> Table/Array STARTS here ...")
ShowTable(val)
SendToAll("<-------- Table/Array ENDS here ...")
elseif type(val) == "string" or type(val) == "number" then
if count ~= nil then
SendToAll(strrep("- ", count*2).."> "..index.." >?< "..val.." it is a "..type(val))
else
SendToAll( "> "..index.." >?< "..val.." it is a "..type(val))
end
end
end
end
and some funny snippet over here ...
function LineStr(str)
local out = ""
local c = nil
for i = 1, strlen(str) do
if c == nil then
c = 1
else c = c +1
end
out = out..gsub(strsub(str, c, c), "(.)", "( "..strsub(str, c, c).." )", 1)
end
str = out
out = nil
return str
end
(G)(e)(e)(!)( )(I)( )(w)(o)(n)(d)(e)(r)( )(w)(h)(a)(t)( )(t)(h)(i)(s)( )(o)(n)(e)( )(d)(o)(e)(s)
This one gives an nice clean time string ....
in the form of " 2 days 3 hours 34 minutes 40 seconds"
it will not show any reduntants ... ex: 0 days.. or 0 minutes ...
[*note*] The initial value ' time ' is in seconds and not miliseconds ....
function DoTimeUnits(time)
local tTimes = {}
local time = time * 1000
if ( time >= 86400000 ) then
repeat
if tTimes[4] then
tTimes[4] = tTimes[4] + 1
else tTimes[4] = 1
end
time = time - 86400000
until time < 86400000
end
if ( time >= 3600000 ) then
repeat
if tTimes[3] then
tTimes[3] = tTimes[3] + 1
else tTimes[3] = 1
end
time = time - 3600000
until time < 3600000
end
if ( time >= 60000 ) then
repeat
if tTimes[2] then
tTimes[2] = tTimes[2] + 1
else tTimes[2] = 1
end
time = time - 60000
until time < 60000
end
if ( time >= 1000 ) then
repeat
if tTimes[1] then
tTimes[1] = tTimes[1] + 1
else tTimes[1] = 1
end
time = time - 1000
until time < 1000
end
local msg = ""
local tTimeUns = { "seconds", "minutes", "hours", "days"}
for i,v in tTimes do
msg = v.." "..tTimeUns[i].." "..msg
end
return msg
end
for the time action above I suspect there is a nicer-shorter way to do it ... I tried something but it needs more work so thats why I post this one ... :)
Any input on this will be mostly appreciated ...
and this one is used so that user can be handled in an appropriate way ... :)
--- // --- Performing action and also informing the user about it ... It is handled from the ' TheAction ' variable ....
function Act(user)
local tActions = {
[1] = function(user) user:SendPM(wsBot, "You will now be disconnected") user:Disconnect() end,
[2] = function(user) user:SendPM(wsBot, "You will now be redirected to "..frmHub:GetRedirectAddress()) user:SendData("$OpForceMove "..frmHub:GetRedirectAddress()) end,
[3] = function(user) user:SendPM(wsBot, "You are kicked") user:Kick() end,
[4] = function(user) user:SendPM(wsBot, "You are temporalily Banned") user:TempBan() end,
[5] = function(user) user:SendPM(wsBot, "You are permenantly Banned") user:Ban() end,
};
for i,v in tActions do
if i == TheAction then
tUsers[user.sName] = nil
return tActions[i](user)
end
end
tActions = nil
end
Can some1 help me with the DoTimeUnits function posted above ? I wanted to see if I could make it nicer but I cant really get anywhere ... I still think there has to be better way . :)
OooOleeeee!!!!!
I found that better way on the DoTimeUnits Function in an earlier post ;)
Here it is ...
function DoTimeUnits(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
To the above function add the snippet found below and witness the perfect uptime string (...lol) with ' !uptime '...
function DataArrival(user, data)
data = strsub(data,1,strlen(data)-1)
local s,e,cmd = strfind( data, "%b<>%s+(%S*)" )
if cmd == "!uptime" then
SendToAll("UpTime", "The "..frmHub:GetHubName().." Hub has been running for"..DoTimeUnits(clock()) )
end
end
QuoteOriginally posted by Herodes
OooOleeeee!!!!!
I found that better way on the DoTimeUnits Function in an earlier post ;)
Here it is ...
function DoTimeUnits(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
To the above function add the snippet found below and witness the perfect uptime string (...lol) with ' !uptime '...
function DataArrival(user, data)
data = strsub(data,1,strlen(data)-1)
local s,e,cmd = strfind( data, "%b<>%s+(%S*)" )
if cmd == "!uptime" then
SendToAll("UpTime", "The "..frmHub:GetHubName().." Hub has been running for"..DoTime(clock()) )
end
end
Great function Herodes , but i bet this one is better than the one you use in the current post ;o)
SendToAll("UpTime", "The "..frmHub:GetHubName().." Hub has been running for"..DoTimeUnits(clock()) )
*** Typhoon?
Thats why I posted it typ ;D
I am glad u like the function ...
dug this one up..
local tmp = clock()
local days, hours, minutes = floor(tmp/86400), floor(mod(tmp/3600, 24)), floor(mod(tmp/60, 60))
considering your code..
instead of multiplying time by 1000, you could just take away the three zeros from the values in tO
and instead of substracting them n times in a loop, you could just use modulo/division once
QuoteOriginally posted by Herodes
Thats why I posted it typ ;D
I am glad u like the function ...
Well , you missed my point , in your version on cmd !uptime you try to call a function that dont exist , thats why i below your post , made the correction...
You call
function DataArrival(user, data)
data = strsub(data,1,strlen(data)-1)
local s,e,cmd = strfind( data, "%b<>%s+(%S*)" )
if cmd == "!uptime" then
SendToAll("UpTime", "The "..frmHub:GetHubName().." Hub has been running for"..DoTime(clock()) )
end
end
But it should be
function DataArrival(user, data)
data = strsub(data,1,strlen(data)-1)
local s,e,cmd = strfind( data, "%b<>%s+(%S*)" )
if cmd == "!uptime" then
SendToAll("UpTime", "The "..frmHub:GetHubName().." Hub has been running for"..DoTimeUnits(clock()) )
end
end
hope you get it now ;)
keep up the good work inhere
*** Typhoon?
QuoteOriginally posted by tezlo
dug this one up..
local tmp = clock()
local days, hours, minutes = floor(tmp/86400), floor(mod(tmp/3600, 24)), floor(mod(tmp/60, 60))
considering your code..
instead of multiplying time by 1000, you could just take away the three zeros from the values in tO
and instead of substracting them n times in a loop, you could just use modulo/division once
hmmm ... but it doesnt modify the ' time ' variable so that the next indexes of tO work on the leftovers from the current index operation ... hope its clear ... I would appreciate the a mod to show me how ...
I had been trying to make it work like that but the maths procedure came hard on me at the time ... ( late in night... ) I'll have another look unless a reply comes faster ...
about the time = time*1000 this is so that I can operate for the seconds in the same way as in days,hours,minutes ... I expected myself to come up with something more ingenious, but ... to no avail.
[*note*] Thx typ ... ;) post edited ...
anyone got a snipplet or standalone Code to insert into a bot that checks for Users that are in Open Hubs and kicks them with a message referring to which rule he broke? (in my example rule Nr. 6).
The Reason is that i'm running a Reg Hub and i don't want my Users running round in Open Hubs seeming though the Authoritys are getting pretty harsh here in Europe
this should work:
-- By NightLitch
DisconnectMessage = "Enter Message Here"
function DataArrival( sUser , sData )
if strsub( sData , 1 , 7 ) == "$MyINFO" then
local _,_,openhubs = strfind( sData , "H:(%d+)" )
if ( openhubs ~= 0 ) then
SendToNick( sUser.sName , DisconnectMessage )
sUser:Disconnect()
end
end
end
/NL
Nightlitch,
H:0 in the description will bypass your script.
I think this will do the trick:
local _,_,openhubs = strfind( sData , ".+H:(%d+)" );
-NotRabidWombat
that.. and you're comparing a string with a number, which will never equal, so everyone gets disconnected
should be: if openhubs ~= "0" then ..
herodes..
this one does :)
function strftime(form, time)
local d, h, m
d, time = floor(time/86400), mod(time, 86400)
h, time = floor(time/3600), mod(time, 3600)
m, time = floor(time/60), mod(time, 60)
return format(form, d, h, m, time)
end
print("uptime: "..strftime("%ddays %dhours %dminutes %dseconds", 90061))
function strftime(form, time)
local d, h, m
d, time = floor(time/86400), mod(time, 86400)
h, time = floor(time/3600), mod(time, 3600)
m, time = floor(time/60), mod(time, 60)
return format(form, d, h, m, time)
end
print("uptime: "..strftime("%ddays %dhours %dminutes %dseconds", 90061))
nasty math lib use ;)
ty tezlo ... I will post an update of the DoTimeUnits later ... I need to find more about that mod(num) lua function as I dont know what it does ... floor(num/num) was hard to figure out ... but I need to know these I suppose....
PS: btw this snippet still comes up with the 0 days 0 hours 15 minutes and so on string ... the DoTimeFunction intends to eliminate reduntant 0 units from the string ... again thx for the input ... :)
QuoteOriginally posted by NightLitch
this should work:
-- By NightLitch
DisconnectMessage = "Enter Message Here"
function DataArrival( sUser , sData )
if strsub( sData , 1 , 7 ) == "$MyINFO" then
local _,_,openhubs = strfind( sData , "H:(%d+)" )
if ( openhubs ~= "0" ) then
SendToNick( sUser.sName , DisconnectMessage )
sUser:Disconnect()
end
end
end
NL
Works great with the 2 missing " 's :)
Just 1 more thing: Can you please add a timer to set that it checks all RegUsers every x minutes just in case they connect to Open Hubs fter they have connected to mine?
this one should be green then:
-- By NightLitch
DisconnectMessage = "Enter Message Here"
function DataArrival( sUser , sData )
if strsub( sData , 1 , 7 ) == "$MyINFO" then
local _,_,openhubs = strfind( sData , ",H:(%d+)" )
if ( tonumber(openhubs) ~= 0 ) then
SendToNick( sUser.sName , DisconnectMessage )
sUser:Disconnect()
end
end
end
Quote
Just 1 more thing: Can you please add a timer to set that it checks all RegUsers every x minutes just in case they connect to Open Hubs fter they have connected to mine?
there's no need to add a timer, the MyINFO string updates in every hub when u connect to another...
DataArrival take's care of it...
Cheers / NightLitch
QuoteOriginally posted by NightLitch
...there's no need to add a timer, the MyINFO string updates in every hub when u connect to another...
DataArrival take's care of it...
Cheers, NightLitch
Oh, ok thnx for the Info and also for the script. Would be interesting to se something like this in Thor in a future release ;) perhaps.
this here is used for extracting the tag from the $MyINFO $ALL nickname description$[...]
you insert the whole descriptiontag string ...
function SplitTagDescr(str)
local tag, descr, tTab = "", "", {}
--- get those letters in the tTab
for i= 1, strlen(str) do
tTab[i] = strsub(str, i,i)
end
--- move backwards until we find a "<"
local i = getn(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
Hello!
Maybe continuing posting code snippets in lua 5/ 5.1 wouldn't be a bad idea...??
WE all wanna learn and i found this thread very usefull for that kind of thing.
Regards