PtokaX forum

Development Section => Your Developing Problems => Topic started by: Herodes on 16 September, 2006, 11:22:08

Title: hmm.. Counting the Time could be better
Post by: Herodes on 16 September, 2006, 11:22:08
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)...
Title: Re: hmm.. Counting the Time could be better
Post by: bastya_elvtars on 16 September, 2006, 11:58:12
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.
Title: Re: hmm.. Counting the Time could be better
Post by: bastya_elvtars on 16 September, 2006, 12:06:46
Hacked a small example script together in a minute.

Code (lua) Select
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)