Sharparam / cybersyn-combinator

Factorio mod adding a specialized combinator for the Project Cybersyn mod
https://mods.factorio.com/mod/cybersyn-combinator
Mozilla Public License 2.0
3 stars 4 forks source link

Allow expressions in item input fields #6

Closed Sharparam closed 1 year ago

Sharparam commented 1 year ago

Personally, I tend to keep a calculator/REPL open on the side for calculating item counts.

Example: I have a station with 8 merged steel chests, each chest holds 288 stacks, I want to fill these with iron plates, which has a stack size of 50.

Ordinarily, I'd have to go to my REPL running outside of the game, and input 50 * 288 * 8 and then use the result for the item request (now that I can input stacks with this mod, the initial 50 * can be skipped).

It would be nice if I could just input this expression directly in the game, so for an item request I could just enter -50 * 288 * 8, or -288 * 8 if using stacks.

Should probably be behind an option, which is disabled by default.

How to implement? Easiest would be to "abuse" Lua's load function, while employing some measures to keep it safe:

-- Input string that would be coming from the textfield
local input = "-50 * 288 * 8"

-- Remove anything that is not maths-related
local expr = string.gsub(input, "[^0-9%.+%-*/%%^()]", "")

-- Make sure to pass empty table for the env to reduce chance of "exploits"
local f, err = load("return " .. expr, nil, "t", {})
if not f then --[[ Handle/display error somehow ]] end

local success, result = pcall(f)
if not success then --[[ Handle/display error somehow ]] end

-- `result` contains the final number
Sharparam commented 1 year ago

Implemented in https://github.com/Sharparam/cybersyn-combinator/commit/8f7e8a3cff712c58174f6ae100ce07706d285cb4