Reference: create a ConTeXt command which takes optional key=value parameters, as well as mandatory parameters
I am trying to make a function which takes a parametric curve and inputs it to a list of segments, which will then be drawn in a separate command.
I'm getting bad argument #1 to 'cos' (number expected, got nil).
How can I correctly input the parametric equations?
% test.tex
\ctxloadluafile{test}
\starttext
\startMPcode
\AppendCurve[
u_start = 0,
u_end = 1,
u_samples = 20,
fx = "math.cos(u)",
fy = "math.sin(u)",
fz = "0"
]
\rendersegments
\stopMPcode
\stoptext
-- test.lua
segments = {}
local settings_to_hash = utilities.parsers.settings_to_hash
local function append_curve(hash
-- u_start
-- ,u_end
-- ,u_samples
-- ,fx,fy,fz
)
local hash = settings_to_hash(hash) or {}
local u_start = hash.u_start or 0
local u_end = hash.u_end or 2*math.pi
local u_samples = hash.u_samples or 3
local fx = hash.fx or math.cos(u)
local fy = hash.fy or math.sin(u)
local fz = hash.fz or 1.5 * math.sin(2 * u)
local u_step = (u_end - u_start) / (u_samples - 1)
local function parametric_curve(u)
return {fx(u),fy(u),fz(u),1}
end
for i = 0, u_samples - 2 do
local u = u_start + i * u_step
local color = (u - u_start) / (u_end - u_start)
local A = parametric_curve(u)
local B = parametric_curve(u + u_step)
-- the tables for surfaces have 5 values
table.insert(segments, {A, B})
end
end
observer = {{0,0,1,1}}
local function render_segments()
for _, seg in ipairs(segments) do
local S3, E3 = seg[1], seg[2]
local Sx, Sy = Sp[1][1], Sp[1][2]
local Ex, Ey = Ep[1][1], Ep[1][2]
tex.print(string.format(
'draw (%.4fcm,%.4fcm) -- (%.4fcm,%.4fcm);',
Sx, Sy, Ex, Ey
))
end
segments = {}
end
interfaces.implement {
name = "rendersegments",
actions = render_segments,
public = true,
arguments = {},
}
interfaces.implement {
name = "AppendCurve",
actions = append_curve,
public = true,
arguments = { "optional" },
}
