Multiplying units by an integer

Place to get help with not working mods / modding interface.
Post Reply
TsumikiMiniwa
Manual Inserter
Manual Inserter
Posts: 3
Joined: Sun Aug 09, 2020 12:15 am
Contact:

Multiplying units by an integer

Post 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

Pi-C
Smart Inserter
Smart Inserter
Posts: 1655
Joined: Sun Oct 14, 2018 8:13 am
Contact:

Re: Multiplying units by an integer

Post 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
A good mod deserves a good changelog. Here's a tutorial (WIP) about Factorio's way too strict changelog syntax!

User avatar
Stargateur
Inserter
Inserter
Posts: 37
Joined: Sat Oct 05, 2019 6:17 am
Contact:

Re: Multiplying units by an integer

Post 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.

Post Reply

Return to “Modding help”