简体   繁体   English

如何在Lua 5.1的32位计算机上实现os.time()兼容性?

[英]How to make os.time() compatibility on a 32bit machine in Lua 5.1?

As a result of the Year 2038 problem( https://en.wikipedia.org/wiki/Year_2038_problem ), we get nil after calling os.time({year=2039, month=1, day=1, hour=0, sec=1}) on a 32bit machine.How to make it compatible in the lua layer,and get result like running on a 64bit machine? 由于2038年的问题( https://en.wikipedia.org/wiki/Year_2038_problem ),我们在调用os.time({year = 2039,month = 1,day = 1,hour = 0, sec = 1})在32位计算机上。如何使其在lua层中兼容,并获得在64位计算机上运行的结果? Is it prosible to write a function like the following? 编写类似以下的函数是否可行? Otherwise, how to achieve it? 否则,如何实现呢?

local function time32Compatibility(timeTable)
    local kMaxYearIn32Bit = 2037;
    if timeTable and timeTable.year and timeTable.year >= kMaxYearIn32Bit then
        local originalTable = clone(timeTable);
        timeTable.year = kMaxYearIn32Bit;
        local deltaTime = calculateDeltaTime(timeTable,originalTable)
        return os.time(timeTable) + kMaxYearIn32Bit*;
    else
        return os.time(timeTable);
    end
end

How to write calculateDeltaTime()? 如何编写calculateDeltaTime()?

local orig_os_time = os.time

function os.time(timeTable)
   if timeTable then
      -- assume that all years divisible by 4 are leap years
      local four_year_ctr = math.floor((timeTable.year - 2000) / 4)
      timeTable.year = timeTable.year - four_year_ctr * 4
      local result = orig_os_time(timeTable) + four_year_ctr * ((365*4+1)*24*60*60)
      timeTable.year = timeTable.year + four_year_ctr * 4
      -- make a correction for non-leap years 2100,2200,2300, 2500,2600,2700,...
      -- subtract ("March 1, 2000" - 12 hours) and divide by 100 "wrong" years
      -- It should work for all time zones from UTC-1200 to UTC+1200
      local centuries = math.floor((result - (951868800 - 12*60*60)) / (25*(365*4+1)*24*60*60))
      local wrong_feb29_ctr = math.floor((centuries * 6 + 7) / 8)
      return result - wrong_feb29_ctr * (24*60*60)
   else
      return orig_os_time()
   end
end

-- Example:
print(os.time{year = 1002017, month = 9, day = 27, hour = 0, min = 0, sec = 0})
-- Will Lua be alive after million years?
-- Will 32-bit Linux systems be alive after 2038?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM