Allow expressions in item input fields
Sharparam opened this issue · 1 comments
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