It is currently September 24th, 2021, 3:55 pm

Some useful function in lua

Discuss the use of Lua in Script measures.
User avatar
death.crafter
Posts: 953
Joined: April 24th, 2021, 8:13 pm

Re: Some useful function in lua

Post by death.crafter »

smurfier wrote: September 12th, 2021, 6:47 pm Just for posterity's sake, here's my scary math version of the AutoScale function. I'm retyping this by converting an old Rainmeter post in Lua, so bear with me if there are typos.

Code: Select all

function AutoScale(num, idp)
	local scales = {'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'}
	local scale = (num == 0) ? 1 : math.ceil(math.log(num) / (10 * math.log(2)))
	local scaled = Round((num / 1024 ^ (scale - 1)), idp or 0)
	return scaled .. ' ' .. scales[scale]
end
Thank you smurfier.

I will soon update the function file with all the functions provided here.
from the Realm of Death
My Current Desktop
User avatar
jsmorley
Developer
Posts: 22310
Joined: April 19th, 2009, 11:02 pm
Location: Fort Hunt, Virginia, USA

Re: Some useful function in lua

Post by jsmorley »

smurfier wrote: September 12th, 2021, 6:47 pm Just for posterity's sake, here's my scary math version of the AutoScale function. I'm retyping this by converting an old Rainmeter post in Lua, so bear with me if there are typos.

Code: Select all

function AutoScale(num, idp)
	local scales = {'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'}
	local scale = (num == 0) ? 1 : math.ceil(math.log(num) / (10 * math.log(2)))
	local scaled = Round((num / 1024 ^ (scale - 1)), idp or 0)
	return scaled .. ' ' .. scales[scale]
end
Don't forget though, that there is no built-in Round() function in Lua:

Code: Select all

function Round(num, idp)
	assert(tonumber(num), 'Round expects a number.')
	local mult = 10 ^ (idp or 0)
	if num >= 0 then
		return math.floor(num * mult + 0.5) / mult
	else
		return math.ceil(num * mult - 0.5) / mult
	end
end
User avatar
smurfier
Moderator
Posts: 1930
Joined: January 29th, 2010, 1:43 am
Location: Willmar, MN

Re: Some useful function in lua

Post by smurfier »

jsmorley wrote: September 12th, 2021, 8:33 pm Don't forget though, that there is no built-in Round() function in Lua:
Once again, for posterity's sake, there's always my version of the Round function.

Code: Select all

function Round(input, idp)
	return tonumber(string.format('%.' .. (idp or 0) .. 'f', input))
end
GitHub | DeviantArt | Tumblr
This is the song that never ends. It just goes on and on my friends. Some people started singing it not knowing what it was, and they'll continue singing it forever just because . . .