Skip to content

Commit

Permalink
Modify Expression constructor API to use varargs
Browse files Browse the repository at this point in the history
  • Loading branch information
jkl1337 committed Feb 21, 2024
1 parent 2b874ae commit cf2ceff
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
19 changes: 9 additions & 10 deletions kiwi.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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*
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions spec/constraint_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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()
Expand Down

0 comments on commit cf2ceff

Please sign in to comment.