hmm.. Counting the Time could be better
 

News:

29 December 2022 - PtokaX 0.5.3.0 (20th anniversary edition) released...
11 April 2017 - PtokaX 0.5.2.2 released...
8 April 2015 Anti child and anti pedo pr0n scripts are not allowed anymore on this board!
28 September 2015 - PtokaX 0.5.2.1 for Windows 10 IoT released...
3 September 2015 - PtokaX 0.5.2.1 released...
16 August 2015 - PtokaX 0.5.2.0 released...
1 August 2015 - Crowdfunding for ADC protocol support in PtokaX ended. Clearly nobody want ADC support...
30 June 2015 - PtokaX 0.5.1.0 released...
30 April 2015 Crowdfunding for ADC protocol support in PtokaX
26 April 2015 New support hub!
20 February 2015 - PtokaX 0.5.0.3 released...
13 April 2014 - PtokaX 0.5.0.2 released...
23 March 2014 - PtokaX testing version 0.5.0.1 build 454 is available.
04 March 2014 - PtokaX.org sites were temporary down because of DDOS attacks and issues with hosting service provider.

Main Menu

hmm.. Counting the Time could be better

Started by Herodes, 16 September, 2006, 11:22:08

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Herodes

function CountTime( int )
	if int < 1000 then return '0 seconds' end; int = math.modf(int/1000)
	local t,ret = { { 'day', 0, 86400 }, { 'hour', 0, 3600 }, { 'minute', 0, 60 } }, '';
	for unit in ipairs( t ) do
		if (int > t[unit][3]) then
			local many = math.modf( int/t[unit][3] );
			SendToAll( t[unit][3]..' fits '..many..' times in '..int..' / '..(many*t[unit][3])..' < '..int ) --- debug
			t[unit][2] = many..' '..t[unit][1]
			if (many > 2) then
				t[unit][2] = t[unit][2]..'s';
			end
			int = int - (many*t[unit][3]);
			t[unit] = t[unit][2]
		else t[unit] = '';
		end
	end
	for i in ipairs(t) do
		if string.len(t[i]) > 0 then
			ret = ret..t[i]..', ';
		end
	end
	return ret..int..' seconds'
end
I am breaking my head with this one ...
How could it be better?
metamethod '__concat' I hear some ppl say,.. but how would I use it ?
I tried this:
setmetatable( t, { __concat = function( a, b ) if string.len(a) > 0 and string.len(b) > 0 then return a..', '..b; end } )

but it give me a stupid 'non-table elements' error when I try to do the table.concat(t)...

bastya_elvtars

#1
Umm, concat metamethod works only with tables. Like if you use this:
__concat=function(t1,t2) dosomething(t1,t2) end


And it is called when you use
t1..t2
, NOT table.concat. And remeber, t1 and t2 are tables.
Everything could have been anything else and it would have just as much meaning.

bastya_elvtars

Hacked a small example script together in a minute.

Code: lua
tbl1={"a","b","c","d"}
tbl2={1,2,3,4}
setmetatable(tbl1,{
  __concat=function(tbl1,tbl2) 
    local result={}
    for k=1,#tbl1 do
      table.insert(result,tbl1[k]..tbl2[k])
    end
    return table.concat(result,", ")
  end
  }
)

print(tbl1..tbl2)
Everything could have been anything else and it would have just as much meaning.

SMF spam blocked by CleanTalk