Page 1 of 1

Multiplying units by an integer

Posted: Sat Feb 26, 2022 7:07 am
by TsumikiMiniwa
Hello,

As the title says, I'd like to multiply a unit by an integer.

Specifically, I'd like to multiply "300kW" by 4, and get either "1200kW", "1.2MW", or (for all I care) "1200000W"

However, units (such as energy units) are strings: https://wiki.factorio.com/Types/Energy

I feel like there's gotta be a builtin for this, or at least a built-in to turn a unit into an integer. Like GetValsFromUnit(unit) and GetValsFromUnit("1200kW") would return 1200000 and "W".

If there isn't, then... damn. Rip.

I'm fully aware that XKCDs 1205, 974, and (in a less extreme sense) 1319 can ALL be invoked, given that I can just put "3MW" in the field that I want filled.

On the other hand, I don't care.

Thanks,

Tsumiki Miniwa

Re: Multiplying units by an integer

Posted: Sat Feb 26, 2022 12:34 pm
by Pi-C
Add

Code: Select all

require("util")
and you'll have access to this function:

Code: Select all

local energy_chars =
{
  k = 10^3,
  K = 10^3,
  M = 10^6,
  G = 10^9,
  T = 10^12,
  P = 10^15,
  E = 10^18,
  Z = 10^21,
  Y = 10^24
}

function util.parse_energy(energy)

  local ending = energy:sub(energy:len())
  if not (ending == "J" or ending == "W") then
    error(ending.. " is not a valid unit of energy")
  end

  local multiplier = (ending == "W" and  1 / 60) or 1
  local magnitude = energy:sub(energy:len() - 1, energy:len() - 1)

  if tonumber(magnitude) then
    return tonumber(energy:sub(1, energy:len()-1)) * multiplier
  end

  multiplier = multiplier * (energy_chars[magnitude] or error(magnitude.. " is not valid magnitude"))
  return tonumber(energy:sub(1, energy:len()-2)) * multiplier

end

Re: Multiplying units by an integer

Posted: Thu Oct 06, 2022 8:42 am
by Stargateur
parse_energy have no doc, it's seem the value is returned in J that a little annoying cause that introduce round issue.