From cf2ceff3495ab257b84c0d8de6d1e60def075b80 Mon Sep 17 00:00:00 2001 From: "John K. Luebs" Date: Wed, 21 Feb 2024 17:10:12 -0600 Subject: [PATCH] Modify Expression constructor API to use varargs --- kiwi.lua | 19 +++++++++---------- spec/constraint_spec.lua | 4 ++-- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/kiwi.lua b/kiwi.lua index 9b50a53..ff31c06 100644 --- a/kiwi.lua +++ b/kiwi.lua @@ -532,7 +532,7 @@ end do --- Expressions are a sum of terms with an added constant. ---@class kiwi.Expression: ffi.cdata* - ---@overload fun(terms: kiwi.Term[], constant: number?): kiwi.Expression + ---@overload fun(constant: number, ...: kiwi.Term): kiwi.Expression ---@field constant number ---@field package term_count number ---@field package terms_ ffi.cdata* @@ -637,17 +637,16 @@ do __index = Expression_cls, } - function Expression_mt.__new(T, terms, constant) - local term_count = terms and #terms or 0 + function Expression_mt.__new(T, constant, ...) + local term_count = select("#", ...) local e = ffi_gc(ffi_new(T, term_count), ckiwi.kiwi_expression_del_vars) --[[@as kiwi.Expression]] e.term_count = term_count - e.constant = constant or 0.0 - if terms then - for i, t in ipairs(terms) do - local dt = e.terms_[i - 1] --[[@as kiwi.Term]] - dt.var = ckiwi.kiwi_var_clone(t.var) - dt.coefficient = t.coefficient - end + e.constant = constant + for i = 1, term_count do + local t = select(i, ...) + local dt = e.terms_[i - 1] --[[@as kiwi.Term]] + dt.var = ckiwi.kiwi_var_clone(t.var) + dt.coefficient = t.coefficient end return e end diff --git a/spec/constraint_spec.lua b/spec/constraint_spec.lua index 137a228..61144c0 100644 --- a/spec/constraint_spec.lua +++ b/spec/constraint_spec.lua @@ -42,7 +42,7 @@ describe("Constraint", function() c = kiwi.Constraint(lhs / 2, nil, "LE", kiwi.strength.MEDIUM) assert.equal("0.5 foo + 0.5 <= 0 | medium", tostring(c)) - c = kiwi.Constraint(lhs, kiwi.Expression(nil, 3), "GE", kiwi.strength.WEAK) + c = kiwi.Constraint(lhs, kiwi.Expression(3), "GE", kiwi.strength.WEAK) assert.equal("1 foo + -2 >= 0 | weak", tostring(c)) end) @@ -68,7 +68,7 @@ describe("Constraint", function() end) it("combines lhs and rhs", function() local v2 = kiwi.Var("bar") - local rhs = kiwi.Expression({ 5 * v2, 3 * v }, 3) + local rhs = kiwi.Expression(3, 5 * v2, 3 * v) local c = kiwi.Constraint(lhs, rhs) local e = c:expression()