|
Mach Modules Documentation
Lua Module API Documentation
|
Go to the source code of this file.
Functions | |
| WrapperModule | OperatorLog (inst, log_msg) |
| Log an operator action to bridgedb and set the Mach4 status message. | |
| WrapperModule | SetStatus (log_msg) |
| Set the Mach4 status bar message using mcCntlSetLastError. | |
| WrapperModule | SendZabbixData (data) |
| WrapperModule | GetMachBuild () |
| Get the Mach4 build number, with caching. | |
| WrapperModule | IsGeneralInput (sig_id) |
| Check whether a signal ID corresponds to a general input signal. | |
| WrapperModule | IsGeneralOutput (sig_id) |
| Check whether a signal ID corresponds to a general output signal. | |
| HandlerA (...) | |
| WrapperModule | AppendArgs (suffix_table,...) |
| WrapperModule | SetCache (category, entry_name, value) |
| Store a value in a named cache category entry. | |
| WrapperModule | GetCache (category, entry_name) |
| Retrieve a named entry from a cache category. | |
| WrapperModule | IsCached (category, entry_name) |
| Check whether a named entry exists in a cache category. | |
| WrapperModule | VerifyCacheExists (category) |
| Ensure that a named cache category exists in the WrapperModule cache. | |
| math | pow (val, exponent) |
| Raise a value to an integer or fractional exponent using the ^ operator. | |
| math | bound (val, minimum, maximum) |
| Clamp a value to within a specified minimum and maximum range. | |
| WrapperModule | SetInstance (instance) |
| Set the active Mach4 instance number. | |
| WrapperModule | SetInstanceToSelectedInstance () |
| Set the active Mach4 instance to the currently selected instance. | |
| WrapperModule | StoreInstance () |
| Save the current active Mach4 instance for later restoration. | |
| WrapperModule | RestoreInstance (inst) |
| Restore the active Mach4 instance to the stored or specified instance. | |
| WrapperModule | GetInstanceCount () |
| Get the total number of active Mach4 instances, with caching. | |
| WrapperModule | IsMultiInstance () |
| Check whether more than one Mach4 instance is running, with caching. | |
| WrapperModule | GetInstanceUnTaged (inst) |
| Return the untagged Mach4 instance number from a potentially tagged instance handle. | |
| WrapperModule | GetUTI (inst) |
| Get the untagged Mach4 instance number (alias for GetInstanceUnTaged). | |
| WrapperModule | UpdateSelectedInstance () |
| Read the selected Mach4 instance from the register and update the cache. | |
| WrapperModule | GetSelectedInstance () |
| Get the currently selected Mach4 instance number. | |
| WrapperModule | SetSelectedInstance (inst) |
| Set the selected Mach4 instance and notify listeners of the change. | |
| WrapperModule | GetInstancesTable (instance) |
| Return a table of valid Mach4 instance numbers based on the input argument. | |
| WrapperModule | GetToolChangerInstance () |
| Get the Mach4 instance number to use for tool changer operations, with caching. | |
| WrapperModule | UpdateToolChangerInstance () |
| Update the cached tool changer instance value from the current OEM parameter. | |
| WrapperModule mcError | GetMsg () |
| Return a human-readable error description string for a Mach4 error code. | |
| WrapperModule mcError | GetMsgCount () |
| Return the number of entries in the Mach4 error code table. | |
| WrapperModule | api_e (meta, api_func,...) |
| Call a Mach4 API function by name with automatic error handling and optional error metadata. | |
| name (string) | |
| Call a Mach4 API function by name with automatic error handling (no metadata). | |
| WrapperModule | api (...) |
| Call a Mach4 API function by name with automatic error handling (no metadata). | |
| WrapperModule | LLLog (logfile, msg,...) |
| Write a timestamped log message with stack traceback to a file. | |
| WrapperModule | SetVersionStrings (_module, url_svn, rev_svn) |
| Extract and store SVN revision and URL keyword strings for a Lua module. | |
| WrapperModule | IsMachInitialized () |
| Check whether the MachMotion plugin has completed its initialization. | |
| WrapperModule | wxMessageBox (message,...) |
| Display a wx modal message box and restore the Mach4 instance context on return. | |
| WrapperModule | MessageBox (message,...) |
| Display a modal message box and restore the Mach4 instance context on return. | |
| WrapperModule | GetValueBit (value, BitIdx) |
| Get the boolean value of the bit at a zero-indexed position in a value. | |
| WrapperModule | SetValueBit (value, BitIdx, state) |
| Set or clear the bit at a zero-indexed position in a value. | |
| WrapperModule | ClearValueBit (value, BitIdx) |
| Clear the bit at a zero-indexed position in a value. | |
| WrapperModule | EnumerateProfileSection (section, inst) |
| Enumerate all key-value pairs in a Mach4 profile section. | |
| WrapperModule | GetCachedSignalHandle (inst, name) |
| Get a signal handle with per-instance caching. | |
| WrapperModule | GetCachedIoHandle (inst, name) |
| Get an I/O handle with per-instance caching. | |
| WrapperModule | GetCachedRegisterHandle (inst, name) |
| Get a register handle with per-instance caching. | |
| WrapperModule | GetSignalHandle (inst, signal_id) |
| Get a cached signal handle for a given signal ID. | |
| WrapperModule | GetIoHandle (inst, Device, IoName) |
| Get a cached I/O handle for a device and I/O name. | |
| WrapperModule | GetRegHandle (inst, Device, RegName) |
| Get a cached register handle for a device and register name. | |
| WrapperModule | ParseRegHandle (path) |
| Parse an I/O or register path string into its device and name components. | |
| WrapperModule | GetSignalState (name, inst) |
| Get the current state of a signal by signal ID. | |
| WrapperModule | eGetSignalState (name, inst) |
| Get the state of a signal by signal ID and raise an error on failure. | |
| WrapperModule | GetSignalInfo (name, inst) |
| Get detailed information about a signal by signal ID. | |
| WrapperModule | SetSignalState (name, val, inst) |
| Set the state of a signal by signal ID. | |
| WrapperModule | eSetSignalState (name, val, inst) |
| Set the state of a signal and raise an error on failure. | |
| WrapperModule | SetSignalEnable (Signal, Value, inst) |
| Enable or disable a signal. | |
| WrapperModule | SignalMap (Signal, Device, IoName, ActiveLow, inst) |
| Map a signal to an I/O point, enable it, and configure its active-low polarity. | |
| WrapperModule | IsSignalMapped (Signal, inst) |
| Check whether a signal is mapped to an I/O point. | |
| WrapperModule | eIsSignalMapped (Signal, inst) |
| Check whether a signal is mapped to an I/O point and raise an error on failure. | |
| WrapperModule | IsSignalMappedAndEnabled (Signal, inst) |
| Check whether a signal is both mapped to an I/O point and enabled. | |
| WrapperModule | eIsSignalMappedAndEnabled (Signal, inst) |
| Check whether a signal is mapped and enabled, and raise an error on failure. | |
| WrapperModule | GetSignalNumber (inst, Device, Description, _debug) |
| Search for a signal by description string within the specified signal device. | |
| WrapperModule | GetIoState (Device, IoName, inst) |
| Get the current state of an I/O point by device and name. | |
| WrapperModule | SetIoState (Device, IoName, val, inst) |
| Set the state of an I/O point by device and name. | |
| WrapperModule | SetAnalogOutput (idx, val, inst) |
| Set the value of an analog output channel. | |
| WrapperModule | GetAnalogOutput (idx, inst) |
| Get the current value of an analog output channel. | |
| WrapperModule | GetAnalogInput (idx, inst) |
| Get the current value of an analog input channel. | |
| WrapperModule | GetRegValue (Device, RegName, inst) |
| Get the numeric value of a register. | |
| WrapperModule | eGetRegValue (Device, RegName, inst) |
| Get the numeric value of a register and raise an error on failure. | |
| WrapperModule | GetRegDesc (Device, RegName, inst) |
| Get the description string of a register. | |
| WrapperModule | eSetRegValue (Device, RegName, val, inst) |
| Set the numeric value of a register and raise an error on failure. | |
| WrapperModule | SetRegValue (Device, RegName, val, inst) |
| Set the numeric value of a register. | |
| WrapperModule | GetRegValueLong (Device, RegName, inst) |
| Get the long integer value of a register. | |
| WrapperModule | SetRegValueLong (Device, RegName, val, inst) |
| Set the long integer value of a register. | |
| WrapperModule | GetRegValueString (Device, RegName, inst) |
| Get the string value of a register. | |
| WrapperModule | SetRegValueString (Device, RegName, val, inst) |
| Set the string value of a register. | |
| WrapperModule | eRegSendCommand (Device, RegName, cmd, inst) |
| Send a register command and raise an error on failure. | |
| WrapperModule | RegSendCommand (Device, RegName, command, inst) |
| Send a command string to a register and return the response. | |
| WrapperModule | GetmcSettingsDevice (inst) |
| Return the device path string for the Mach4 core settings device. | |
| WrapperModule | DoesOEMParamExist (RegName, inst) |
| Check whether an OEM parameter register exists for the specified instance. | |
| WrapperModule | GetOEMParamDesc (RegName, inst) |
| Get the description string of an OEM parameter register. | |
| WrapperModule | GetOEMParamValue (RegName, inst) |
| Get the numeric value of an OEM parameter register. | |
| WrapperModule | eGetOEMParamValue (RegName, inst) |
| Get an OEM parameter numeric value and raise an error on failure. | |
| WrapperModule | GetOEMRegValue (RegName, inst) |
| Get the numeric value of an OEM register. | |
| WrapperModule | eGetOEMRegValue (RegName, inst) |
| Get an OEM register numeric value and raise an error on failure. | |
| WrapperModule | GetOEMParamValueCached (RegName, inst) |
| Get the numeric value of an OEM parameter register with per-instance caching. | |
| WrapperModule | eGetOEMParamValueCached (RegName, inst) |
| Get a cached OEM parameter numeric value and raise an error on failure. | |
| WrapperModule | SetOEMParamValue (RegName, val, inst) |
| Set the numeric value of an OEM parameter register. | |
| WrapperModule | eSetOEMParamValue (RegName, val, inst) |
| Set an OEM parameter value and raise an error on failure. | |
| WrapperModule | SetOEMRegValue (RegName, val, inst) |
| Set the numeric value of an OEM register. | |
| WrapperModule | eSetOEMRegValue (RegName, val, inst) |
| Set an OEM register value and raise an error on failure. | |
| WrapperModule | GetOEMParamValueString (RegName, inst) |
| Get the string value of an OEM parameter register. | |
| WrapperModule | eGetOEMParamValueString (RegName, inst) |
| Get an OEM parameter string value and raise an error on failure. | |
| WrapperModule | GetOEMRegValueString (RegName, inst) |
| Get the string value of an OEM register. | |
| WrapperModule | eGetOEMRegValueString (RegName, inst) |
| Get an OEM register string value and raise an error on failure. | |
| WrapperModule | GetOEMParamValueStringCached (RegName, inst) |
| Get the string value of an OEM parameter register with per-instance caching. | |
| WrapperModule | eGetOEMParamValueStringCached (RegName, inst) |
| Get a cached OEM parameter string value and raise an error on failure. | |
| WrapperModule | SetOEMParamValueString (RegName, val, inst) |
| Set the string value of an OEM parameter register. | |
| WrapperModule | eSetOEMParamValueString (RegName, val, inst) |
| Set an OEM parameter string value and raise an error on failure. | |
| WrapperModule | ToBoolean (value) |
| Convert any value to a boolean using Mach4 convention rules. | |
| WrapperModule | BoolToNumber (value) |
| Convert a boolean value to its numeric equivalent (1 or 0). | |
| WrapperModule | GetOEMParamValueBool (RegName, inst) |
| Get the value of an OEM parameter register as a boolean. | |
| WrapperModule | SetOEMParamValueBool (RegName, value, inst) |
| Set an OEM parameter value to a boolean (stored as 1 or 0). | |
| WrapperModule | GetOEMParamValueBit (ParamName, BitIdx, inst) |
| Get the value of a specific bit from an OEM parameter. | |
| WrapperModule | GetOEMRegValueBit (RegName, BitIdx, inst) |
| Get the value of a specific bit from an OEM register. | |
| WrapperModule | SetOEMParamValueBit (ParamName, BitIdx, state, inst) |
| Set or clear a specific bit in an OEM parameter value. | |
| WrapperModule | SetOEMRegValueBit (RegName, BitIdx, state, inst) |
| Set or clear a specific bit in an OEM register value. | |
| WrapperModule | ClearOEMParamValueBit (ParamName, BitIdx, inst) |
| Clear a specific bit in an OEM parameter value. | |
| WrapperModule | SetOEMRegValueString (RegName, val, inst) |
| Set the value of a register to a string. | |
| WrapperModule | ClearOEMRegValueBit (RegName, BitIdx, inst) |
| Clear a specific bit in an OEM register value. | |
| WrapperModule | ParseIOSigPath (path, default_instance) |
| Parse an encoded I/O signal or register path string into a structured object table. | |
| WrapperModule | GetOEMParamIOSigObject (SigName, inst) |
| Retrieve and cache the IOSig object referenced by an OEM parameter register string value. | |
| WrapperModule | GetParamIOSigObject (Device, SigName, inst) |
| Retrieve and cache the IOSig object referenced by a parameter register string value. | |
| WrapperModule | GetOEMParamRegObject (ParamName, inst) |
| Retrieve and cache the register object referenced by an OEM parameter register string value. | |
| WrapperModule | GetParamRegObject (Device, ParamName, inst) |
| Retrieve and cache the register object referenced by a parameter register string value. | |
| WrapperModule | GetOEMParamSig (SigName, inst) |
| Get the current state of a signal or I/O point referenced by an OEM parameter register. | |
| WrapperModule | eGetOEMParamSig (SigName, inst) |
| Get the state of a signal or I/O point referenced by an OEM parameter register and raise an error on failure. | |
| WrapperModule | GetParamSig (Device, SigName, inst) |
| Get the current state of a signal or I/O point referenced by a parameter register. | |
| WrapperModule | eGetParamSig (Device, SigName, inst) |
| Get the state of a signal or I/O point referenced by a parameter register and raise an error on failure. | |
| WrapperModule | SetOEMParamSig (SigName, Val, inst) |
| Set the state of a signal or I/O point referenced by an OEM parameter register. | |
| WrapperModule | eSetOEMParamSig (RegName, val, inst) |
| Set an OEM parameter signal and raise an error if the operation fails. | |
| WrapperModule | SetParamSig (Device, SigName, Val, inst) |
| Set the state of a signal or I/O point referenced by a parameter register. | |
| WrapperModule | eSetParamSig (Device, SigName, Val, inst) |
| Set a parameter signal and raise an error if the operation fails. | |
| WrapperModule | AddOEMParamSignalToOutputIgnoreList (src_oemparamsig, target_lists, inst) |
| Add an OEM parameter output signal to one or more output ignore lists if it is a valid general output. | |
| WrapperModule | AddOutputToOutputIgnoreLists (sig_id, target_lists, inst) |
| Add an output signal number to one or more OEM parameter output ignore lists. | |
| WrapperModule | AddOutputToAllOutputIgnoreLists (sig_id, inst) |
| Add a general output signal to all standard output ignore lists for all Mach4 instances. | |
| WrapperModule | IsOEMParamSigMapped (SigName, inst) |
| Check whether an OEM parameter signal register has a meaningful (non-empty) value mapped to it. | |
| WrapperModule | IsParamSigMapped (Device, SigName, inst) |
| Check whether a parameter signal register has a meaningful (non-empty) value mapped to it. | |
| WrapperModule | ParseRegisterPath (EncodedPath, default_instance) |
| Parse an encoded register path string into a structured table. | |
| WrapperModule | ParseAnalogSignalPath (EncodedPath, default_instance) |
| Parse an encoded analog input or output path string into a structured table. | |
| WrapperModule | GetOEMParamReg (ParamName, inst) |
| Get the value of a register or analog signal pointed to by an OEM parameter register object. | |
| WrapperModule | SetOEMParamReg (ParamName, Val, inst) |
| Set the value of a register or analog output pointed to by an OEM parameter register object. | |
| WrapperModule | SetMachEnable (value) |
| Enable or disable the Mach4 software enable for all instances. | |
| WrapperModule | SetDriveEnable (val, inst) |
| Set the drive enable signal state for the specified Mach4 instance. | |
| WrapperModule | SetDriveEnableAll (val) |
| Set the drive enable signal state for all Mach4 instances. | |
| WrapperModule | GetDriveEnable (inst) |
| Get the current state of the drive enable signal for the specified instance. | |
| WrapperModule | SetHardwareEnable (val, inst) |
| Set the hardware enable signal state for the specified Mach4 instance. | |
| WrapperModule | SetHardwareEnableAll (val) |
| Set the hardware enable signal state for all Mach4 instances. | |
| WrapperModule | GetHardwareEnable (inst) |
| Get the current state of the hardware enable signal for the specified instance. | |
| WrapperModule | RequestData (StructType, inst) |
| Request structured data from the MachMotion plugin via a command register. | |
| WrapperModule | DoesParameterExist (param, inst) |
| Check whether a Mach4 control parameter exists, with caching. | |
| WrapperModule | RequireParameterExist (param, inst) |
| Log a warning if the specified Mach4 control parameter does not exist. | |
| WrapperModule | GetParameterCacheName (param, inst) |
| Return the cache category name string for a given Mach4 control parameter and instance. | |
| WrapperModule | SetParameter (param, value, inst) |
| Set the value of a Mach4 control parameter and update the cache. | |
| WrapperModule | SetParameterBit (param, bit, value, inst) |
| Set a specific bit of a Mach4 control parameter to a given state. | |
| WrapperModule | GetParameter (param, inst) |
| Get the current value of a Mach4 control parameter and update the cache. | |
| WrapperModule | GetParameterCached (param, inst) |
| Get the value of a Mach4 control parameter, using cached values in screen chunks. | |
| WrapperModule | GetParameterBit (param, bit, inst) |
| Get the value of a specific bit from a Mach4 control parameter. | |
| WrapperModule | GetParameterBitCached (param, bit, inst) |
| Get the value of a specific bit from a Mach4 control parameter, using cached values in screen chunks. | |
| WrapperModule | IsProbeEnabledOutputOn (inst) |
| Check whether the probe enable output signal is currently active. | |
| WrapperModule | IsProbeErrorInputOn (inst) |
| Check whether the probe error input signal is currently active. | |
| WrapperModule | EnableProbeOutput (delay, inst) |
| Activate the probe enable output signal and optionally wait for the probe error input to clear. | |
| WrapperModule | DisableProbeOutput (inst) |
| Deactivate the probe enable output signal if it is configured. | |
| WrapperModule | FilterProbePositions () |
| Placeholder function that always raises an error when called. | |
| WrapperModule | RegenerateToolPathDialog (non_modal, inst) |
| Display a modal or non-modal tool path regeneration progress dialog. | |
| UI | clean_up () |
| Clean up the tool path regeneration dialog timer and close the dialog. | |
| WrapperModule | SendGMSCommand (reg_name, command) |
| Send a command to the GlobalMonitoringSystem plugin via a register command. | |
| WrapperModule | GetGMSClassNumber (class) |
| Get the numeric class code for a GMS message class. | |
| WrapperModule | GetGMSClassName (class) |
| Get the display name string for a GMS message class. | |
| WrapperModule | CreateSystemGlobalMessage (Table) |
| Create a GMS system global monitor message with conditions, actions, and optional extra content. | |
| Recursive (t) | |
| Recursively write a condition set and all nested sub-sets to the GMS command string. | |
| WrapperModule | CreateSingleMessage (Table) |
| Create a single-execution GMS monitor message (deprecated - use CreateSystemGlobalMessage). | |
| WrapperModule | CreateGMSDialog (Table) |
| Create an independent GMS dialog with title, description, and optional extra content panels. | |
| WrapperModule | CreateGMSNotification (Text, Title, Time, GroupBox, CloseBtn, Size, Red, Green, Blue) |
| Add a text notification entry to the GMS notification bar. | |
| WrapperModule | UpdateNotification (Identifier, Text) |
| Update the text of an existing GMS notification. | |
| WrapperModule | SetNotificationBackgroundColour (Identifier, rr, gg, bb) |
| Set the background color of an existing GMS notification. | |
| WrapperModule | WriteToGMSLog (Text, Class) |
| Write a text entry to the GMS log without displaying any dialog. | |
| WrapperModule | CloseGMSNotification (Handle) |
| Close a GMS notice or notification created by CreateGMSDialog or CreateGMSNotification. | |
| WrapperModule | CloseGMSMessage (Handle) |
| Close a GMS alert caused by a message from CreateSystemGlobalMessage. | |
| WrapperModule | SetWarningMessage (Message, TimeOut, EveryWhere, Title, Size, inst) |
| Display a warning message notification in the GMS notification bar. | |
| WrapperModule | GetGMSWarnings () |
| Check whether any GMS warnings are currently active. | |
| WrapperModule | GetGMSAlarms () |
| Check whether any GMS alarms are currently active. | |
| WrapperModule | GetGMSAlarmsAndWarnings () |
| Check whether any GMS alarms or warnings are currently active. | |
| WrapperModule | UpdateGMSClass (Handle, Class) |
| Update the class (severity level) of an existing GMS global message. | |
| WrapperModule | UpdateGMSTitle (Handle, Text) |
| Update the title text of an existing GMS global message. | |
| WrapperModule | UpdateGMSDescription (Handle, Text) |
| Update the description text of an existing GMS global message. | |
| WrapperModule | FullyDisableGMSMessage (Handle, disable) |
| Permanently disable or re-enable a GMS monitor message. | |
| WrapperModule | DisableGMSMessage (Handle, disable) |
| Temporarily disable or re-enable a GMS monitor message. | |
| WrapperModule | GetGMSHandleFromTitle (title) |
| Retrieve the GMS monitor handle for the first message found with the given title. | |
| WrapperModule | GetReloadCounter () |
| Retrieve the current value of the MachMotion configuration reload counter. | |
| WrapperModule | IncrementReloadCounter () |
| Increment the MachMotion configuration reload counter register. | |
| WrapperModule | IsMachMotionLicensed () |
| Check whether the MachMotion base feature is licensed. | |
| WrapperModule | IsGMSLicensed () |
| Check whether the GMS feature is licensed. | |
| WrapperModule | IsYaskawaLicensed () |
| Check whether the Yaskawa feature is licensed. | |
| WrapperModule | IsLatheCCLicensed () |
| Check whether the LatheCC feature is licensed. | |
| WrapperModule | IsRMPLicensed () |
| Check whether the RMP feature is licensed. | |
| WrapperModule | IsGrinderCCLicensed () |
| Check whether the GrinderCC feature is licensed. | |
| WrapperModule | IsFeatureLicensed (feature_name) |
| Check whether a named MachMotion feature is licensed via the plugin command register. | |
| WrapperModule | CheckIfLicensed (inst, feature_name) |
| Check whether a named feature is licensed in the Mach4 license file. | |
| WrapperModule | GetFeatureKey (feature) |
| Return the numeric key for a named MachMotion license feature. | |
| WrapperModule | EvaluateLuaExpression (expr_string) |
| Evaluate a simple Lua expression that returns a value or series of values. | |
| WrapperModule | RunLuaString (expr_string) |
| Run an arbitrary sized chunk of Lua code. | |
| WrapperModule | GetAlarmMessage (e, extra) |
| Format an error object or string into a GMS alarm message string. | |
| WrapperModule | ErrorMessage (msg_or_obj, appendmessage) |
| Format an error object or string into a human-readable error message string. | |
| WrapperModule debug | GetParameters (stack_frame) |
| Retrieve all named local variables and their values from the specified stack frame. | |
| WrapperModule debug | BriefParameterList (stack_frame) |
| Return a comma-delimited string of parameter name(value) pairs for a stack frame. | |
| WrapperModule debug | GetNextUsefulStackFrame (starting_frame) |
| Find the next stack frame index that has a meaningful function name. | |
| WrapperModule debug | GetCallStack (start_frame) |
| Return a multi-line string representation of the current Lua call stack. | |
| WrapperModule debug | GetFunctionName (fn_obj, default, get_qualified_name) |
| Look up the cached name for a function object. | |
| WrapperModule debug | AddToFunctionNameMap (tables) |
| Add function-to-name mappings to the cache without clearing existing entries. | |
| WrapperModule debug | UpdateFunctionNameMap (tables, dont_clear_cache) |
| Rebuild the cached mapping of function objects to qualified name strings. | |
| WrapperModule | GetLocalVariable (stack_frame, var_name) |
| Return the value of a named local variable from a previous stack frame. | |
| WrapperModule | ErrorHandler (err) |
| xpcall error handler that normalizes any error value into a rich error object | |
| WrapperModule | pcall (fn,...) |
| Protected function call wrapper that ensures error objects include a full call stack. | |
| WrapperModule | Error (msg, data) |
| Raise a Lua error with a rich error object containing stack trace and machine context. | |
| err | GetMachInfo () |
| Format the Mach4 machine state information as a human-readable multi-line string. | |
| err | GetMessage () |
| Return the primary error message string from the error object. | |
| err | GetVersionInfo () |
| Collect version information strings from the module table into the error object. | |
| name (parameters) | |
| Format the error object's debug call stack as a human-readable multi-line string. | |
| err | GetTraceback () |
| Format the error object's debug call stack as a human-readable multi-line string. | |
| err | GetAlarmMessage () |
| Build a GMS alarm message table from the error object for display or delivery. | |
| WrapperModule | MCodeError (msg, filename, line) |
| Construct and raise a Mach4 M-code error with macro context information. | |
| WrapperModule | AlarmError (obj, FileName, Line, ForceAlarm) |
| Construct and invoke a GMS alarm from obj. | |
| WrapperModule | AlarmMessage (Message, FileName, Line, ForceAlarm) |
| Invoke a GMS alarm message with protected error handling. | |
| WrapperModule | GetMotionController () |
| Retrieve the name of the currently configured motion controller device. | |
| WrapperModule | IsSimMotionController () |
| Check whether the current motion controller is a simulator device. | |
| WrapperModule | MakeNewFileQueue () |
| Create and return a new LuaFileQueue instance for the current Mach directory. | |
| WrapperModule | PostCommand (command_name, as_opr_panel, wait_for_response, inst) |
| Post a named user command to the file queue for execution. | |
| WrapperModule | PostToFileQueue (command_string, wait_for_response, inst) |
| Post a Lua command string to the file queue for asynchronous execution. | |
| WrapperModule | WaitForFileQueueResponse (handle, check_func, inst) |
| Block until a file queue command receives a reply or the machine is disabled. | |
| WrapperModule | GetFileQueueSleepTime () |
| Return the sleep interval in milliseconds used when polling the file queue for responses. | |
| WrapperModule | ParseMultipleReturnValuesFromFileQueueResponse (value_from_user) |
| Parse a comma-delimited key:value string from a file queue response into a structured table. | |
| WrapperModule | PretendCommandsAreFromOperatorPanels () |
| Determine whether screen commands should be treated as operator panel commands. | |
| WrapperModule | RunUserCommandFromOperatorPanel (command_name) |
| Execute a named user command as if it originated from an operator panel. | |
| WrapperModule | RunUserCommand (command_name, from_opr_panel) |
| Execute a named user command, optionally treating it as coming from an operator panel. | |
| WrapperModule | CreateFunctionFromCommand (command_name) |
| Create an executable function closure from a named user command. | |
| WrapperModule | CleanUserCommandName (command_name) |
| Sanitize a user command name by removing special characters. | |
| WrapperModule | GetActiveCommands () |
| Retrieve all currently active commands and their usage counts. | |
| WrapperModule | GetActiveFeedbacks () |
| Retrieve all currently active command feedbacks and their usage counts. | |
| WrapperModule | GetAllCommands () |
| Retrieve all registered commands from m.Commands and all user command INI files. | |
| WrapperModule | GetAllFeedbacks () |
| Retrieve all registered command feedback functions from m.CommandFeedbacks and user.UserCommandsFeedback. | |
| WrapperModule | GetAllActions () |
| Retrieve all registered command action functions from m.CommandActions and user.UserCommands. | |
| WrapperModule | WriteCommandFile () |
| Write the current command, feedback, and action lists to all registered command receiver registers. | |
| WrapperModule | GetCommandDeviceName () |
| Return the device name string used for the Commands device. | |
| WrapperModule | GetCommandRegisterName (name) |
| Return the register name string for a command entry in the Commands device. | |
| WrapperModule | GetCommandIOName (name) |
| Return the I/O name string for a command entry in the Commands device. | |
| WrapperModule | GetCommandFeedbackRegisterName (name) |
| Return the register name string for a command feedback entry in the Commands device. | |
| WrapperModule | GetCommandFeedbackIOName (name) |
| Return the I/O name string for a command feedback entry in the Commands device. | |
| WrapperModule | IncrementCommandUsage (command_name) |
| Increment the usage counter for a named command in the Commands device register. | |
| WrapperModule | DecrementCommandUsage (command_name) |
| Decrement the usage counter for a named command in the Commands device register. | |
| WrapperModule | IncrementCommandFeedbackUsage (feedback_name) |
| Increment the usage counter for a named command feedback in the Commands device register. | |
| WrapperModule | DecrementCommandFeedbackUsage (feedback_name) |
| Decrement the usage counter for a named command feedback in the Commands device register. | |
| WrapperModule | OpenFileHelper () |
| Load and return the FileHelper module. | |
| WrapperModule | GetUserCommandFolder () |
| Return the folder path where user command INI files are stored. | |
| WrapperModule | GetUserCommandFilename (command_name) |
| Return the full file path for a named user command's INI file. | |
| WrapperModule | GetAllUserCommands () |
| Read and return all user command configuration tables from the UserCommands folder. | |
| WrapperModule | ReadUserCommandFile (filepath) |
| Read and parse a user command INI file into a table of command configuration tables. | |
| WrapperModule | GetUserCommand (command_name) |
| Retrieve a single user command configuration table by name. | |
| WrapperModule | SaveUserCommand (command_table) |
| Save a command configuration table to its INI file in the UserCommands folder. | |
| WrapperModule | DeleteAllUserCommands () |
| Delete all user command INI files from the UserCommands folder. | |
| WrapperModule | GetDefaultCommand (name) |
| Return a default command configuration table for the given command name. | |
| WrapperModule | CreateUserCommandFeedbackOption (name, func) |
| Register a user command feedback function in user.UserCommandsFeedback. | |
| WrapperModule | CreateUserCommandActionOption (name, func) |
| Register a user command action function in user.UserCommands. | |
| WrapperModule | CreateSimpleUserCommand (cmd_name, action_name, feedback_name) |
| Create, save, and register a simple user script command with action and feedback options. | |
| WrapperModule | CreateCommandFeedbackOption (name, func) |
| Register a pre-canned command feedback option in the m.CommandFeedbacks table. | |
| WrapperModule | CreateCommandActionOption (name, func) |
| Register a pre-canned command action option in the m.CommandActions table. | |
| WrapperModule | CreateCommand (cmd_table) |
| Register a command table entry in the m.Commands registry. | |
| WrapperModule | CreateSimpleCommand (cmd_name, action_name, feedback_name) |
| Create and register a simple pre-canned command with action and feedback options. | |
| WrapperModule | SetCommandButtonLabels (cmd_name, off_label, on_label) |
| Set the on and off button label text for a command. | |
| WrapperModule | SetCommandButtonColors (cmd_name, off_color, on_color) |
| Set the on and off background colors for a command's button. | |
| WrapperModule | SetCommandButtonTextColors (cmd_name, off_color, on_color) |
| Set the on and off text colors for a command's button. | |
| WrapperModule | SetCommandFeedbackPeriod (cmd_name, period_sec) |
| WrapperModule | GetPreCannedFeedbackNames () |
| Retrieve the names of all registered pre-canned command feedback options. | |
| WrapperModule | GetPreCannedActionNames () |
| Retrieve the names of all registered pre-canned command action options. | |
| WrapperModule | ProcessActiveCommands () |
| Process all active commands and feedbacks, refreshing their states each screen update. | |
| WrapperModule | ProcessActiveCommand (command_name, command_table) |
| Process a single active command's feedback state and update its target if the state changed. | |
| WrapperModule | ProcessActiveCommandFeedback (feedback_name) |
| Process the feedback state for a single named feedback and update its associated I/O output. | |
| WrapperModule | GetCommandFeedbackState (command_table) |
| Retrieve the current feedback state for a command based on its FeedbackSourceType. | |
| WrapperModule | SetCommandTargetState (command_name, command_table, feedback_state) |
| Update the feedback target signal or I/O state for a command and its associated I/O point. | |
| WrapperModule | GetAllInputSignals () |
| Retrieve all input signals registered in the current Mach4 instance. | |
| WrapperModule | GetAllOutputSignals () |
| Retrieve all output signals registered in the current Mach4 instance. | |
| WrapperModule | GetAllSignals (input) |
| Retrieve all input or output signals registered in the current Mach4 instance. | |
| WrapperModule | GetSignalUserDescription (signal) |
| Get the user-configured description for a signal, by name or signal ID. | |
| WrapperModule | GetAllDevices (filter) |
| Retrieve all registered devices of a specified type. | |
| WrapperModule | GetAllIOPaths () |
| Retrieve full device/IO path strings for all I/O points across all devices. | |
| WrapperModule | GetAllIOForDevice (device_handle) |
| Retrieve all I/O points registered under a specific device handle. | |
| WrapperModule | CreateRegister (dev_name, reg_name, other_info) |
| Dynamically create a register via the MachMotion plugin. | |
| WrapperModule | RemoveRegister (dev_name, reg_name) |
| Remove the permanent registration of a dynamically-created register. | |
| WrapperModule | CreateIO (dev_name, io_name, is_input, other_info) |
| Dynamically create an I/O point via the MachMotion plugin. | |
| WrapperModule | CreateInput (dev_name, io_name, other_info) |
| Create a dynamic input I/O point via the MachMotion plugin. | |
| WrapperModule | CreateOutput (dev_name, io_name, other_info) |
| Create a dynamic output I/O point via the MachMotion plugin. | |
| WrapperModule | RemoveIO (dev_name, io_name) |
| Remove the permanent registration of a dynamically-created I/O point. | |
| WrapperModule | JoinArgs (args, delim, start_index) |
| Join variadic arguments into a delimited string. | |
| func_name () | |
| Checkpoint-instrumented wrapper function template for long-running operations. | |
| WrapperModule DbgCheckPoint | new () |
| Create a new DbgCheckPoint instance with the specified name. | |
| WrapperModule DbgCheckPoint | update_recent () |
| Update the recency tracking table for the given checkpoint id. | |
| WrapperModule DbgCheckPoint | CHECK (descr, value) |
| Record a checkpoint with an optional description and value. | |
| WrapperModule DbgCheckPoint | tostring () |
| Format the checkpoint state as a human-readable multi-line string. | |
| WrapperModule | Protected (...) |
| Execute a function with protected call handling, showing full debug error dialogs on failure. | |
| WrapperModule | ProtectedMsg (...) |
| Execute a function with protected call handling, showing simplified error dialogs when not debugging. | |
| WrapperModule | ProtectedChk (chk, clean_message,...) |
| Execute a function with protected call handling, showing error dialogs on failure. | |
| w | JoinArgs (_args, "; ", 2) |
| Join variadic arguments into a delimited string. | |
| WrapperModule | IsDebugging (inst) |
| Return whether MachMotion debugging mode is currently active. | |
| WrapperModule | SetStopStatus (inst) |
| Record the current machine stop/disable counter value for later comparison. | |
| WrapperModule | SetStopStatusAll () |
| Update the stop status register for all available Mach4 instances. | |
| WrapperModule | CheckStopStatus (Filename, LineNumber, inst) |
| Check whether the machine stop/disable status has changed since it was last recorded. | |
| WrapperModule | FunctionError (CustomMessage, FunctionName, LineNumber, FileName) |
| Log a function error with context information and return a formatted error message string. | |
| WrapperModule | FunctionCompleted (CustomMessage, FunctionName, LineNumber, FileName) |
| Log function completion with context information and return a formatted status message. | |
| WrapperModule | MessageDialog (Message, Title, DialogType) |
| Display a modal dialog with a message and configurable button layout. | |
| WrapperModule | GetNetworkAdapters () |
| Retrieve the names and IP addresses of all network adapters on this machine. | |
| WrapperModule | ShowNetworkAdapters () |
| Display all network adapter names and IP addresses in a message box. | |
| WrapperModule | EscapeCSV (s) |
| Escape a string value for safe inclusion in a CSV field. | |
| WrapperModule | FromCSVToTable (s) |
| Convert a single CSV line string into a Lua table of field values. | |
| WrapperModule | FromMultiLineCSVToTable (s) |
| Convert a multi-line CSV string into a two-dimensional Lua table. | |
| WrapperModule | TabletoCSV (tt) |
| Convert a sequential table of values into a comma-separated CSV string. | |
| WrapperModule | ReadCSV (FileName, options) |
| WrapperModule | WriteCSV (Table, FileName, WriteMode) |
| Write a two-dimensional table of data to a CSV file. | |
| WrapperModule | ReadCSVIntoTableByHeader (filename, options) |
| WrapperModule | WriteLines (Table, FileName, WriteMode) |
| Write an array of strings to a file, with optional append mode. | |
| WrapperModule | WriteTextFile (TextString, FileName, WriteMode) |
| Write a string to a text file, with optional append mode. | |
| WrapperModule | ReadTextFile (FileName) |
| Read the entire contents of a text file into a string. | |
| WrapperModule | AddLine (Table, WriteString) |
| Append a string as a new line to a table used for file writing. | |
| WrapperModule | ParseCSVLine (line, sep) |
| Parse a single CSV line string into an array of field values. | |
| WrapperModule | UpdateRecentCSVs (filename) |
| Update the list of recently used CSV files stored in the Mach4 profile. | |
| WrapperModule | parseINI (name) |
| Parse an INI-format file into a nested Lua table. | |
| WrapperModule | saveINI (name, t) |
| Save a nested table as an INI-format file. | |
| WrapperModule | CopyTables (from, to) |
| Copy all key-value pairs from one table into another, merging matching keys. | |
| WrapperModule | AppendTables (from, to) |
| Append all array elements from one table to the end of another table. | |
| WrapperModule | DeepCopy (from, to) |
| Perform a deep copy of a table, recursively duplicating nested tables. | |
| WrapperModule | TableLength (tbl) |
| Count the number of key-value pairs in a table using pairs() iteration. | |
| WrapperModule | GetKeysSortedByValue (tbl, sortFunction) |
| Return an array of table keys sorted by their associated values. | |
| sortFunction (a, b) | |
| Default sort comparator used by GetKeysSortedByValue to sort keys by their associated table values. | |
| WrapperModule | TableToString (tbl, indent, terse, linesep, depth, seen) |
| Convert a table to a human-readable string representation resembling JSON. | |
| WrapperModule | Round (num, idp, nearestupdown) |
| Round a number to a specified number of decimal places, with directional control. | |
| WrapperModule | nice_decimal (value, precision, width) |
| Format a number as a readable decimal string, removing insignificant trailing zeros. | |
| WrapperModule | ParseStructuredGCodeComment (comment_string) |
| Parse a structured G-code comment string into comment text and an optional Lua data expression. | |
| WrapperModule | ReadGcodeHeaderParameters (gcode_file) |
| Parse structured key-value parameter blocks from a G-code file header. | |
| WrapperModule | IsGCodeFileLoadedInAnotherInstance (filename, inst) |
| Check whether a given G-code file is already loaded in any other Mach4 instance. | |
| WrapperModule | IsGCodeFileLoaded (inst) |
| Check whether a G-code file is currently loaded in the specified instance. | |
| WrapperModule | LoadGCodeFile (filename, inst) |
| Loads a GCode file into the specified instance. | |
| WrapperModule | ParseGCodeLine (Line, Keywords) |
| Parse a G-code line string and extract numeric values for specified keywords. | |
| WrapperModule | StripGCodeLine (Line, Keywords) |
| Remove specified G-code word/value pairs (by keyword) from a G-code line string. | |
| WrapperModule | StripModals (Line, Modals) |
| Removes specified modal G-code and M-code commands from a G-code line. | |
| WrapperModule | HasModal (Line, Modal) |
| Check whether a G-code line contains a specific modal code. | |
| WrapperModule | tostring (number, format_number) |
| Convert a number to a string with specified decimal precision, removing scientific notation. | |
| WrapperModule | tointstring (number) |
| Convert a value to an integer string, rounding floats to the nearest integer. | |
| WrapperModule | toint (number) |
| Convert a value to a Lua integer, attempting intelligent type coercion. | |
| WrapperModule | tonumber (number, format_number) |
| Convert a value to a formatted number with specified decimal precision. | |
| WrapperModule | GetTableCount (T) |
| Count the number of entries in a table, including non-integer keys. | |
| WrapperModule | StringFormat (commandString, number, format_string, postString, debugging) |
| Format a number with a G-code command prefix and optional suffix into a string. | |
| WrapperModule | Scale (Input, InputMIN, InputMAX, OutputMIN, OutputMAX) |
| Scale an input value from one numeric range to another. | |
| WrapperModule | Sleep (msTime, sleep_per_iteration, IgnoreStopStatus) |
| Pause execution for specified milliseconds while monitoring machine state. | |
| WrapperModule | Yield (yield_events) |
| Yield execution to the event loop one or more times, preventing UI freezing. | |
| WrapperModule | WaitForSignal (Signal, State, Timeout, AlarmMessage, inst) |
| Wait for a signal to reach a specified state with timeout and machine disable detection. | |
| WrapperModule | WaitForOEMParamSig (Signal, State, Timeout, AlarmMessage, inst) |
| Wait for an OEM parameter signal to reach a specified state with timeout and machine disable detection. | |
| WrapperModule | eWaitForOEMParamSig (Signal, State, Timeout, AlarmMessage, inst) |
| Wait for an OEM parameter signal to reach a specified state, raising errors instead of returning failure. | |
| WrapperModule | WaitForIoState (Device, IoName, State, Timeout, AlarmMessage, inst) |
| Wait for an I/O point to reach a specified boolean state, with timeout and machine disable detection. | |
| WrapperModule | WaitForRegisterValue (Device, RegName, Value, Timeout, AlarmMessage, inst) |
| Wait for a register value to equal a specified value, with timeout and machine disable detection. | |
| WrapperModule | FindFile (filename, directory, ext_table, inst) |
| Recursively search a directory tree for a file matching the given name and extension. | |
| WrapperModule | FileExists (FileName) |
| Check whether a file exists and is accessible for reading. | |
| WrapperModule | FileRename (old_name, new_name) |
| Rename or move a file from one path to another. | |
| WrapperModule | DirectoryExists (Path) |
| Check to see if a directory exists. | |
| WrapperModule | MakeDirectory (Path) |
| Create the target directory and all nonexistent ancestor directories. | |
| WrapperModule | FileSizeBytes (filepath) |
| Get the size of a file in bytes using the Lua File System library. | |
| WrapperModule | FileSizeKilobytes (filepath) |
| Get the size of a file in kilobytes. | |
| WrapperModule | FileSizeMegabytes (filepath) |
| Get the size of a file in megabytes. | |
| WrapperModule | RunBatchCode (batch_code_to_run, description, verbosity) |
| Write and execute batch code in a temporary CMD script file. | |
| WrapperModule | CreateOrOpenFile (path_to_file, contents, editor) |
| Create a file with default contents if it does not exist, then open it in an external editor. | |
| WrapperModule | CreateOrOpenSubroutine (sub_name, sub_contents) |
| Create a stub subroutine file if it does not exist, then open it in an editor. | |
| WrapperModule | NPPEditor (path_to_nppexe) |
| Create a batch code generator function for opening a file in Notepad++. | |
| WrapperModule | GCEditEditor (path_to_gceditexe) |
| Create a batch code generator function for opening a file in GCEdit. | |
| WrapperModule | FindNotepadPP (skip_registry) |
| Attempt to locate the installation path of Notepad++, caching the result. | |
| WrapperModule | GetRotatedPosition (x_machine, y_machine, angle) |
| Calculate rotated coordinates using G68 rotation parameters. | |
| WrapperModule | GetUnrotatedPosition (x_machine, y_machine, angle) |
| Calculate unrotated coordinates by reversing G68 rotation. | |
| WrapperModule | RotateAroundPoint (x, y, angle, x_center, y_center) |
| Rotate a point (x, y) by the specified angle around a center point. | |
| WrapperModule | GetRotatedPartPos (X, Y, InvertRotation) |
| Calculate the rotated XY position accounting for G68 coordinate rotation. | |
| WrapperModule | FindClosestPath (CurrentX, CurrentY) |
| Find the G-code line whose path segment is closest to the current or specified XY position. | |
| WrapperModule | FindPath (LineNum, XPos, YPos) |
| Find the closest point on a G-code path segment to a given XY position. | |
| WrapperModule | IsToolPathGenerating (inst) |
| Check whether the tool path is currently being generated for the specified instance. | |
| WrapperModule | FunctionButtonMDI (Command, inst) |
| Execute an MDI command after verifying machine state and prompting for cycle start confirmation. | |
| WrapperModule | MDICommand (Command, PushPop, Message, OverrideDisable, inst) |
| Execute an MDI command on the selected instance with an optional Please Wait dialog. | |
| WrapperModule | MDICommandNoDialog (Command, PushPop, Message, OverrideDisable, inst) |
| Execute an MDI command on the selected instance without displaying a confirmation dialog. | |
| WrapperModule | ReadListHistory (filename) |
| Read a list history file and return its contents as an array of strings. | |
| WrapperModule | AddToListHistory (filename, list_line) |
| Append a new line to a list history file, maintaining a maximum of 200 entries. | |
| WrapperModule | CreateToolInfoFile () |
| Create a default ToolInfo.lua file and initialize the TOOL_NAMES global table. | |
| WrapperModule | GetToolInfo (ToolName, Attribute) |
| Retrieve a specific attribute from the TOOL_NAMES configuration table by tool name. | |
| WrapperModule | GetToolName (Number) |
| Get the display name of a tool based on its tool number. | |
| WrapperModule | PasswordProtection (level) |
| Prompt the user to enter a password for the specified protection level, granting or denying access. | |
| WrapperModule | LogoutPassword () |
| Clear the stored password session so the user must re-enter their password. | |
| WrapperModule | GenericTextEntry (message, title) |
| Display a modal text entry dialog and return the value entered by the user. | |
| WrapperModule | PleaseWaitDialog (WaitType, WaitMessage, WaitDataInvert, WaitData1, WaitData2, WaitData3) |
| Display a "Please Wait" modal dialog while waiting for a specified condition to be met. | |
| UI | UpdatePleaseWaitDialog () |
| Poll the active wait condition and close the dialog if the condition is met or an error occurs. | |
| UI | ClosePleaseWaitDialog (EndModalCode) |
| Enforce a minimum display time then end the PleaseWait dialog modal session. | |
| UI | CancelPleaseWaitDialog () |
| Handle user cancellation of the PleaseWait dialog, performing context-appropriate cleanup. | |
| UI | ClosePleaseWaitDialog () |
| Close the PleaseWait dialog by delegating to _ClosePleaseWaitDialog() with error handling. | |
| WrapperModule | WaitOnCondition (WaitType, WaitMessage, WaitDataInvert, WaitData1, WaitData2, WaitData3) |
| Wait for a specified condition without displaying a dialog, polling until the condition is met. | |
| UpdateWaitOnCondition () | |
| Poll the current wait condition and return a status code indicating whether it has been met. | |
| WrapperModule | GetControlLicensedModules (License) |
| Check whether a specific license module bit is active in the Mach4 control license. | |
| WrapperModule | GetControlLicensedVersion () |
| Get the licensed version name of the Mach4 control software. | |
| WrapperModule | PackagePath (paths, update_cpath) |
| WrapperModule | Load (basename, path_dir, force) |
| Load a named Lua module from a subdirectory of the Mach installation directory. | |
| WrapperModule | LoadOpStatus (force) |
| Load the OpStatus module if it has not already been loaded. | |
| WrapperModule | LoadVersionInfo () |
| Load the machine version information from the MachBuildVer.lua file into a global table. | |
| WrapperModule | GetVersionInfo (component) |
| Get a specific component value from the loaded machine version information table. | |
| WrapperModule | IsOperatorPanelJogging (axis) |
| Check whether the operator panel is actively jogging a specific axis. | |
| WrapperModule | IsHardwareOperatorPanelEnabled () |
| Check whether at least one hardware (non-software, non-IOControl) operator panel is configured. | |
| WrapperModule | GetConfiguredOperatorPanels () |
| Retrieve all configured operator panel entries from the Mach4 profile. | |
| panels | GetOperatorPanel (PartNumber) |
| Find a configured operator panel entry by part number. | |
| WrapperModule | GetOperatorPanelPartNumber (id) |
| Look up operator panel hardware information by numeric ID. | |
| WrapperModule | GetControlConfiguration (ModelArray) |
| Get the machine control configuration model number, dispatching to the correct schema version. | |
| WrapperModule | GetControlConfiguration_v2 (ModelArray) |
| Build and return the machine model number string using v2 screen configuration. | |
| WrapperModule | GetControlConfiguration_v1 (ModelArray) |
| Build and return the machine model number string using v1 screen configuration. | |
| WrapperModule | DistanceFunction (A1, A2, B1, B2, C1, C2) |
| Calculate the Euclidean distance between two points in up to three dimensions. | |
| WrapperModule | GcodeInterpGetPos (InterpTool) |
| Get the G-code interpreter's interpolated XY position adjusted for X/Y tool offsets. | |
| WrapperModule | GetMachSetupUnits (inst) |
| Retrieve the setup unit system configured for the Mach4 machine profile. | |
| WrapperModule | ConvertFromSetupUnits (value, ToUnits) |
| Convert a value from setup units to the specified unit system (typically current units). | |
| WrapperModule | ConvertFromCurrentUnits (value, ToUnits) |
| Convert a value from current units to the specified unit system (typically setup units). | |
| WrapperModule | ConvertFromMetricToCurrentUnits (value) |
| Convert a value from metric units to the current unit system. | |
| WrapperModule | ConvertFromImperialToCurrentUnits (value) |
| Convert a value from imperial units to the current unit system. | |
| WrapperModule | GetToleranceAmount (level, amount) |
| Get the tolerance amount for position comparisons based on level or explicit value. | |
| WrapperModule | IsAxisPositionInTolerancePart (AxisID, RequestedPosition, Tolerance) |
| Check whether the current axis part-coordinate position is within tolerance of a requested position. | |
| WrapperModule | IsAxisPositionInTolerancePartLastOutput (AxisID, RequestedPosition, Tolerance) |
| Check whether an axis part-coordinate position (last output) is within tolerance of a requested position. | |
| WrapperModule | IsAxisPositionInToleranceMachine (AxisID, RequestedPosition, Tolerance) |
| Check whether the current axis machine-coordinate position is within tolerance of a requested position. | |
| WrapperModule | IsAxisPositionInToleranceMachineLastOutput (AxisID, RequestedPosition, Tolerance) |
| Check whether an axis machine-coordinate position (last output) is within tolerance of a requested position. | |
| WrapperModule | CalculateTotalAppliedOffset (axis_id, ToUnits) |
| Calculate the total coordinate offset applied to an axis, in the specified unit system. | |
| WrapperModule | ConvertMachinePositionToPartPosition (axis, machineposition, UnitSystem) |
| Convert a machine-coordinate position to a part-coordinate position. | |
| WrapperModule | ConvertPartPositionToMachinePosition (axis, partposition, UnitSystem) |
| Convert a part-coordinate position to a machine-coordinate position. | |
| WrapperModule | GetAxisPos (AxisID, position) |
| Get the part-coordinate position of an axis in current units. | |
| WrapperModule | GetAxisMachinePos (AxisID, position) |
| Get the machine-coordinate position of an axis. | |
| WrapperModule | IsAxisRotary (AxisID, inst) |
| Determine whether a given axis is a rotary (angular) axis. | |
| WrapperModule | GetProgrammedFeedRate () |
| Get the programmed feed rate in current units per minute. | |
| WrapperModule | TimeToMove (distance, units) |
| Calculate the time in milliseconds required to travel a given distance at the current feed rate. | |
| WrapperModule | GetDefaultUnitsModal () |
| Get the G-code modal string representing the machine's default unit system. | |
| WrapperModule | GetGCodeCNTL1MST (inst) |
| Get the current state of the G-code CNTL1 MST (suppress M/S/T waits) bit. | |
| WrapperModule | SetGCodeCNTL1MST (inst) |
| Set the G-code CNTL1 MST bit to suppress M/S/T waits. | |
| WrapperModule | ResetGCodeCNTL1MST (inst) |
| Clear the G-code CNTL1 MST bit to re-enable M/S/T waits. | |
| WrapperModule | GCodeCNTL1MSTToggle (inst) |
| Toggle the G-code CNTL1 MST (suppress M/S/T waits) bit on or off. | |
| WrapperModule | GetNearestRotation (axis, angle, part_position, inst) |
| Get the nearest absolute position for a rotary axis to reach a target angle. | |
| WrapperModule | GetCurrentFixtureIndex (inst) |
| Get the current active fixture index (G54 = 1, G55 = 2, etc.). | |
| WrapperModule | GetNearestRotationFixedDirection (axis, angle, part_position, inst) |
| Get the nearest position on a fixed-direction rotary axis to a target angle, ensuring forward-only motion. | |
| WrapperModule | CalculateCarouselPathScore (distance_deg, final_cumulative_deg, current_cumulative_deg) |
| Calculate a weighted score for a carousel rotation path (lower score is better). | |
| WrapperModule | IsCarouselPathViable (current_cumulative_deg, movement_deg) |
| Check whether a proposed carousel movement stays within the configured rotation limits. | |
| WrapperModule | CalculateCarouselAngularDistances (from_deg, to_deg) |
| Calculate the clockwise and counter-clockwise angular distances between two positions on a 360-degree carousel. | |
| WrapperModule | GetCarouselRotationWithLimits (axis, target_angle, part_position, inst) |
| Calculate the optimal carousel rotation target considering cumulative rotation limits. | |
| WrapperModule | GetCarouselCumulativeRotation (axis, part_position, inst) |
| Get the current cumulative rotation in degrees for a carousel axis. | |
| WrapperModule | GetNearestModValue (value, mod_value, offset) |
| Get the nearest modular boundary value (multiple of mod_value plus offset) to a given value. | |
| WrapperModule | GetNextModValue (value, mod_value, offset) |
| Get the smallest multiple of mod_value (plus offset) that is strictly greater than value. | |
| WrapperModule | GetPreviousModValue (value, mod_value, offset) |
| Get the largest multiple of mod_value (plus offset) that is less than or equal to value. | |
| WrapperModule | InhibitJogOnCoordinatedAxes (inst) |
| Inhibit jogging on all coordinated axes (mc.X_AXIS through mc.C_AXIS). | |
| WrapperModule | ReleaseInhibitJogOnCoordinatedAxes (inst) |
| Release the jog inhibit on all coordinated axes (mc.X_AXIS through mc.C_AXIS). | |
| WrapperModule | InhibitJogOnAllAxes (inst) |
| Inhibit jogging on all axes (mc.AXIS0 through mc.MC_MAX_AXES-1). | |
| WrapperModule | ReleaseInhibitJogOnAllAxes (release_all, inst) |
| Release the jog inhibit on all axes (mc.AXIS0 through mc.MC_MAX_AXES-1). | |
| WrapperModule | InhibitJogOnAxis (axis, inst) |
| Increment the jog inhibit counter for a specific axis, preventing jogging. | |
| WrapperModule | ReleaseInhibitJogOnAxis (axis, release_all, inst) |
| Decrement the jog inhibit counter for a specific axis, enabling jogging when it reaches zero. | |
| WrapperModule | IsInhibitJogOnAxis (axis, inst) |
| Check whether jogging is currently inhibited for a specific axis. | |
| WrapperModule | GetMinimumJogRatePercentage (axis, inst) |
| Calculate the minimum jog rate percentage for an axis based on motor encoder resolution. | |
| WrapperModule | GetMinimumJogFeedrate (axis, inst) |
| Get the minimum jog feedrate for an axis in setup units per minute. | |
| WrapperModule | GetMaximumJogFeedrate (axis, inst) |
| Get the maximum jog feedrate for an axis in setup units per minute. | |
| WrapperModule | TemporaryMachineState (actions) |
| Create a temporary machine state object that saves and restores the machine state. | |
| WrapperModule _TemporaryMachineState | Revert () |
| Revert the machine state to the saved state and return any passed values. | |
| WrapperModule | IsLimitSwitchActive (inst) |
| Check whether any limit switch is currently active across all mapped motors. | |
| WrapperModule | IsHomeSwitchActive (homing_axis, inst) |
| Check whether a home switch is currently active for a specific axis or any axis. | |
| WrapperModule | IsAxisHomed (AxisID, IgnoreSaftyCheck, inst) |
| Check whether a specific axis is homed, respecting OEM homing safety parameters. | |
| WrapperModule | VerifyAllAxesAreHomed (IgnoreSaftyCheck, inst) |
| Verify that all enabled axes are homed, respecting the HomingSafetyCheck OEM parameter. | |
| WrapperModule | VerifyAllAxesAreHomedCached (inst) |
| Check if all enabled axes are homed using cached axis state data. | |
| WrapperModule | MarkAxisAsHomedIfMotorsAreHomed (AxisID, inst) |
| Mark an axis as homed if all of its mapped motors report as homed. | |
| WrapperModule | GetMotorParentAxisID (MotorID, inst) |
| Find the axis ID that a given motor is mapped to. | |
| WrapperModule | IsMotorMappedToAxis (AxisID, MotorID, inst) |
| Check whether a specific motor is mapped to a specific axis. | |
| WrapperModule | GetAxisChildMotorID (AxisID, inst) |
| Get an array of all motor IDs mapped to a specified axis. | |
| WrapperModule | IsAxisEnabled (AxisID, inst) |
| Check whether a specific axis is enabled in Mach4. | |
| WrapperModule | ApplyMotorMappingsToMotionController (inst) |
| Apply current motor mappings to the motion controller plugin. | |
| WrapperModule | MapMotorsToAxis (AxisID, MotorID, inst) |
| Map a motor to an axis, enabling the axis and unmapping the motor from any prior axis. | |
| WrapperModule | UnMapMotorsFromAxis (AxisID, MotorID, inst) |
| Unmap a motor (or all motors) from an axis and disable the axis if no motors remain. | |
| WrapperModule | GetMotorCountsPerUnitFromProfile (MotorID, inst) |
| Get the counts-per-unit value for a motor from the Mach4 profile. | |
| WrapperModule | SetMotorCountsPerUnitFromProfile (MotorID, value, inst) |
| Set the counts-per-unit value for a motor in the Mach4 profile. | |
| WrapperModule | GetMotorSoftMaxLimitFromProfile (MotorID, inst) |
| Get the soft maximum limit for a motor from the Mach4 profile in setup units. | |
| WrapperModule | SetMotorSoftMaxLimitFromProfile (MotorID, value, inst) |
| Set the soft maximum limit for a motor in the Mach4 profile. | |
| WrapperModule | GetMotorSoftMinLimitFromProfile (MotorID, inst) |
| Get the soft minimum limit for a motor from the Mach4 profile in setup units. | |
| WrapperModule | SetMotorSoftMinLimitFromProfile (MotorID, value, inst) |
| Set the soft minimum limit for a motor in the Mach4 profile. | |
| WrapperModule | GetMotorMaxVelocityFromProfile (MotorID, inst) |
| Get the maximum velocity for a motor from the Mach4 profile in setup units per minute. | |
| WrapperModule | SetMotorMaxVelocityFromProfile (MotorID, value, inst) |
| Set the maximum velocity for a motor in the Mach4 profile. | |
| WrapperModule | GetMotorMaxAccelFromProfile (MotorID, inst) |
| Get the maximum acceleration for a motor from the Mach4 profile in setup units per second squared. | |
| WrapperModule | SetMotorMaxAccelFromProfile (MotorID, value, inst) |
| Set the maximum acceleration for a motor in the Mach4 profile. | |
| WrapperModule | GetAxisSoftMaxLimitFromProfile (AxisID, inst) |
| Get the soft maximum limit for an axis in setup units, derived from the first mapped motor. | |
| WrapperModule | GetAxisSoftMinLimitFromProfile (AxisID, inst) |
| Get the soft minimum limit for an axis in setup units, derived from the first mapped motor. | |
| WrapperModule | GetMotorPositionInSetupUnits (MotorID, inst) |
| Get the current motor position in setup units. | |
| WrapperModule | GetToolChangerData (inst) |
| Read tool changer configuration data from the CSV and OEM parameters. | |
| WrapperModule | GetCalculatedManualToolSetterPosition (tool_setter_height, inst) |
| Calculate the machine Z position of a manual tool setter for tool length measurement. | |
| WrapperModule | GetCalculatedAutoToolSetterPosition (inst) |
| Trigger an automatic tool setter measurement by executing M901. | |
| WrapperModule | GetDefaultSpindle (inst) |
| Get the default spindle number from the OEM parameters. | |
| WrapperModule | GetSelectedSpindle (inst) |
| Get the currently selected spindle number. | |
| WrapperModule | SetSelectedSpindle (spindle, inst) |
| Set the selected spindle number and persist the change. | |
| WrapperModule | GetToolChangeStatus (attribute, spindle, inst) |
| Get a named tool change status attribute for a spindle. | |
| WrapperModule | SetToolChangeStatus (attribute, value, spindle, inst) |
| Set a named tool change status attribute for a spindle. | |
| WrapperModule | GetSelectedToolPocket (spindle, inst) |
| Get the pocket number of the currently selected (staged) tool. | |
| WrapperModule | GetCurrentToolPocket (spindle, inst) |
| Get the current tool pocket number from the configured memory source. | |
| WrapperModule | SetCurrentToolPocket (pocket_number, spindle, inst) |
| Set and persist the current tool pocket number. | |
| WrapperModule | SetPreviousToolPocket (pocket_number, spindle, inst) |
| Store the previous tool pocket number in the tool change status. | |
| WrapperModule | GetPreviousToolPocket (spindle, inst) |
| Get the previously active tool pocket number for a spindle. | |
| WrapperModule | GetMaxToolPocketNumber (spindle, inst) |
| Get the maximum number of tool pockets configured for a spindle. | |
| WrapperModule | SetSelectedTool (ToolNumber, inst) |
| Set the selected (staged) tool number for the next tool change. | |
| WrapperModule | GetSelectedTool (inst) |
| Get the tool number currently selected (staged) for the next tool change. | |
| WrapperModule | GetCurrentTool (inst) |
| Get the tool number currently loaded in the spindle. | |
| WrapperModule | SetCurrentTool (ToolNumber, inst) |
| Set the current tool number and update all relevant Mach4 state. | |
| WrapperModule | SetPreviousTool (PreviousTool, inst) |
| Store the previous tool number in the tool change status. | |
| WrapperModule | GetPreviousTool (inst) |
| Get the previously active tool number. | |
| WrapperModule | GetLastToolChangeStatus (spindle, inst) |
| Get the success or failure status of the last tool change operation. | |
| WrapperModule | GetMaxToolNumber (inst) |
| Get the maximum number of tools configured in the Mach4 profile. | |
| WrapperModule | GetPocketToolNumber (Pocket, inst) |
| Find the tool number currently assigned to a given pocket number. | |
| WrapperModule | IsToolChangerOverrideOn (tool_number, inst) |
| Check whether a tool changer override is active for a given tool number. | |
| WrapperModule | GetToolChangerOverride (tool_number, inst) |
| Get the tool changer override mode string for a given tool number. | |
| WrapperModule | GetToolSetterManualName (inst) |
| Get the currently selected manual tool setter name. | |
| WrapperModule | SetToolSetterManualName (name, inst) |
| Set the manual tool setter selection by name and persist the change to the profile. | |
| WrapperModule | GetToolSetterAutoName (inst) |
| Get the currently selected auto tool setter name. | |
| WrapperModule | SetToolSetterAutoName (name) |
| Set the auto tool setter selection by name and persist the change to the profile. | |
| WrapperModule | GetFixtureSetterManualName (inst) |
| Get the currently selected manual fixture setter name. | |
| WrapperModule | SetFixtureSetterManualName (name, inst) |
| Set the manual fixture setter selection by name and persist the change to the profile. | |
| WrapperModule | GetFixtureSetterAutoName (inst) |
| Get the currently selected auto fixture setter name. | |
| WrapperModule | SetFixtureSetterAutoName (name, inst) |
| Set the auto fixture setter selection by name and persist the change to the profile. | |
| WrapperModule | GetToolSetterHeight (ToolSetterName) |
| Get the stored height value of a named tool setter. | |
| WrapperModule | SetToolSetterHeight (ToolSetterName, Height) |
| Set the height of a named tool setter and persist the change to the profile. | |
| WrapperModule | GetToolSetterPosition (ToolSetterName) |
| Get the stored Z position of a named tool setter. | |
| WrapperModule | SetToolSetterPosition (ToolSetterName, Position) |
| Set the Z position of a named tool setter and persist the change to the profile. | |
| WrapperModule | GetToolSetterType (ToolSetterName) |
| Get the type string ("Auto" or "Manual") for a named tool setter. | |
| WrapperModule | GetToolSetterProbeInput (ToolSetterName) |
| Get the probe input index for a named tool setter. | |
| WrapperModule | GetToolSetterFixturesOffsets (ToolSetterName) |
| Check whether fixture offsets are enabled for a named tool setter. | |
| WrapperModule | GetToolSetterFixtureOffsetMode (ToolSetterName) |
| Get the fixture offset mode for a named tool setter. | |
| WrapperModule | GetToolSetterProbeInputSignal (ToolSetterName) |
| Get the Mach4 signal constant for the probe input of a named tool setter. | |
| WrapperModule | GetToolSetterProbeName (ToolSetterName) |
| Get the G-code probe command name for a named tool setter. | |
| WrapperModule | GetToolSetterSoftlimitsEnabled (ToolSetterName) |
| Check whether soft limits are enabled for a named tool setter. | |
| WrapperModule | IsToolSetterAuto (ToolSetterName) |
| Check whether a named tool setter is configured as an automatic setter. | |
| WrapperModule | GetToolSetterGoToPositionName (ToolSetterName) |
| Get the GoTo position name to move to before tool touchoff for a named tool setter. | |
| WrapperModule | GetToolSetterEndGoToPositionName (ToolSetterName) |
| Get the GoTo position name to move to after tool touchoff for a named tool setter. | |
| WrapperModule | IsAutoToolSetterEnabled () |
| Check whether at least one automatic tool setter is configured. | |
| WrapperModule | IsManualToolSetterEnabled () |
| Check whether at least one manual tool setter is configured. | |
| WrapperModule | GetAllAutoToolSetters () |
| Retrieve all configured automatic tool setters. | |
| WrapperModule | GetAllManualToolSetters () |
| Retrieve all configured manual (non-auto) tool setters. | |
| WrapperModule | GetAllToolSetters () |
| Read all configured tool setters from the Mach4 profile and return them as a keyed table. | |
| WrapperModule | WriteToolSetter (ini_table) |
| Write a tool setter configuration table to the Mach4 profile and flush changes. | |
| WrapperModule | GetToolSetter (name) |
| Retrieve a tool setter configuration table by name. | |
| WrapperModule | CreateToolSetter (name) |
| Create a new tool setter entry or return the existing one if the name already exists. | |
| WrapperModule | GetToolSetterPosition (AutoManual) |
| Get the stored Z position of a named tool setter. | |
| WrapperModule | SetToolSetterPosition (AutoManual, Position) |
| Set the Z position of a named tool setter and persist the change to the profile. | |
| WrapperModule | ClearProbeFeedbackPositions () |
| Reset all probe feedback position OEM parameters to the Mach4 nil pound variable value. | |
| WrapperModule | GetProbeFeedbackPositions (positionnumber) |
| Retrieve a stored probe feedback position value by position index. | |
| WrapperModule | SetProbeFeedbackPositions (positionnumber, val) |
| Store a probe feedback position value in the OEM parameter for a given position index. | |
| WrapperModule | PrintDebugMessage (CustomMessage, OpenMessageDialog, FileName, LineNumber) |
| Print a debug message to the Mach4 log and optionally show a dialog, when debugging is enabled. | |
| WrapperModule | LogF (fmt,...) |
| Log a printf-style formatted message using string.format(). | |
| WrapperModule | LogC (...) |
| Log all provided values concatenated into a single space-delimited message. | |
| WrapperModule | LogMultiline (message, indent) |
| Log a multi-line message by splitting on newlines and logging each line separately. | |
| WrapperModule | DeleteMachMotionLogFile () |
| Delete the MachMotion.log file from the Mach4 directory. | |
| WrapperModule | AppendToFile (logfile, msg) |
| Append a message string followed by a newline to a log file. | |
| WrapperModule | Log (CustomMessage, FileName, LineNumber, CallerLevel, inst) |
| Write a message to the Mach4 log and the MachMotion.log file with caller context. | |
| WrapperModule | SrcLoc () |
| Return both the source file name and line number of the immediate caller. | |
| name (s) | |
| Get the function name of the Lua caller at the specified stack level, skipping pcall frames. | |
| WrapperModule | GetCurrFnName (caller_level) |
| Get the function name of the Lua caller at the specified stack level, skipping pcall frames. | |
| WrapperModule | GetCurrFileName (caller_level) |
| Get the source file name of the Lua script at the specified caller stack level. | |
| WrapperModule | GetCurrLineNo (caller_level) |
| Get the current line number of the Lua source file at the specified caller stack level. | |
| WrapperModule | InterpretRangeString (range_string) |
| Parse a range string of comma-delimited numbers and ranges into a flat array of integers. | |
| WrapperModule | VerifyMinimumMachVersion (version_string) |
| Verify that the running Mach4 version meets a specified minimum version requirement. | |
| WrapperModule | SplitVersionString (version_string) |
| Split a period-or-comma-delimited version string into an array of pieces. | |
| WrapperModule array | tointeger (tbl) |
| Convert all elements of an array to integers using math.tointeger(). | |
| WrapperModule string | split (str, sSeparator, nMax, bRegexp) |
| Split a delimited string into an array of substrings. | |
| WrapperModule table | concat (tbl, sep, i, j) |
| Concatenate all elements of a table into a string, coercing non-string values via tostring(). | |
| WrapperModule table | deepcopy (orig, copies) |
| Create a deep copy of a table, preserving metatables and handling circular references. | |
| WrapperModule table | merge (t1, t2) |
| Merge table t2 into table t1, preferring entries from t2 on conflict. | |
| WrapperModule table | val_to_str (v) |
| Convert a value to a compact string for use in table.repr() output. | |
| WrapperModule table | key_to_str (k) |
| Convert a table key to a compact string for use in table.repr() output. | |
| WrapperModule table | repr (tbl) |
| Produce a compact, single-line Lua-parsable string representation of a table. | |
| WrapperModule table pretty | val_to_str (v, indent, has_key) |
| Convert a value to an indented string for use in pretty-printed output. | |
| WrapperModule table pretty | key_to_str (k, indent) |
| Convert a table key to an indented string for use in pretty-printed output. | |
| WrapperModule table pretty | repr (tbl, indent, has_key) |
| Produce a human-readable, indented Lua-parsable representation of a table. | |
| WrapperModule | IsCycleStartHoldActive () |
| Check whether a Cycle Start Hold is currently active. | |
| WrapperModule | RequestCycleStartHold () |
| Request a Cycle Start Hold if one is not already active. | |
| WrapperModule | ReleaseCycleStartHold (reason) |
| Release the active Cycle Start Hold and log the release reason. | |
| WrapperModule | ReleasedForCycleStart () |
| Check whether the most recent Cycle Start Hold release was triggered by Cycle Start. | |
| WrapperModule | SetCycleStartPressedFlag () |
| Set the Cycle Start Pressed Flag and record the activation time. | |
| WrapperModule | ResetCycleStartPressedFlag () |
| Clear the Cycle Start Pressed Flag and mark it as inactive. | |
| WrapperModule | IsCycleStartPressedFlagSet () |
| Check whether the Cycle Start Pressed Flag is currently set. | |
| WrapperModule | UpdateCycleStartPressedFlag () |
| Update the Cycle Start Pressed Flag, resetting it if its active time has elapsed. | |
| WrapperModule | StopCustomCntlDwellBar () |
| Stop the custom CNC dwell bar by forwarding to the screen module or writing -1 to the OEM parameter. | |
| WrapperModule | StartCustomCntlDwellBar (dwellbartable) |
| Start the custom CNC dwell bar with the given configuration table. | |
| WrapperModule | SetCustomCntlDwellBarValue (value) |
| Set the current value of the custom CNC dwell bar. | |
| WrapperModule | GetCustomCntlDwellBarValue () |
| Get the current value of the custom CNC dwell bar. | |
| WrapperModule | IsTableInRegister (inst) |
| Check whether a serialized Lua table is currently stored in the table register. | |
| WrapperModule | ReadTableRegister (inst) |
| Read and clear the raw table string from the shared table register. | |
| WrapperModule | SendTableAcrossRegister (luatable, inst) |
| Serialize and write a Lua table into the shared table register. | |
| WrapperModule | ReceiveTableAcrossRegister (inst) |
| Read and deserialize a Lua table from the table register if one is available. | |
| WrapperModule | ReceiveTableAcrossRegisterWait (inst) |
| Wait for a Lua table to appear in the table register, then read and return it. | |
| WrapperModule | GetMCodeHoldCount () |
| Get the current MCode hold counter value. | |
| WrapperModule | IncrementMCodeHoldCount () |
| Increment the MCode hold counter by one. | |
| WrapperModule | DecrementMCodeHoldCount () |
| Decrement the MCode hold counter by one, with a floor of zero. | |
| WrapperModule | IsMCodeHoldActive () |
| Check whether an MCode hold is currently active. | |
| WrapperModule | RequestMCodeHold () |
| Increment the MCode hold counter, requesting a hold. | |
| WrapperModule | ReleaseMCodeHold () |
| Decrement the MCode hold counter, releasing one hold request. | |
| WrapperModule | WaitOnCycleStart (Message) |
| Pause G-code execution and wait for cycle start to resume. | |
| WrapperModule | SetSoftLimits (OnOff, inst) |
| Enable or disable soft limits for all coordinated axes. | |
| WrapperModule | GetSoftLimits (inst) |
| Get the current soft limits on/off state. | |
| WrapperModule | IsAxisInSideSoftLimitsZone (AxisID, inst) |
| Check whether the axis current machine position is within its soft limit zone. | |
| WrapperModule | IsAxisMachinePositionInSideSoftLimitsZone (AxisID, position, inst) |
| Check whether a specified machine position is within the soft limit zone for an axis. | |
| WrapperModule | MoveAxisIntoSoftLimitZone (AxisID, margin, inst) |
| Move the specified axis into the soft limit zone if it is currently outside. | |
| WrapperModule | ConfigureToolSpecificSoftLimits (current_tool, inst) |
| Apply tool-specific soft limit values from the tool table to active machine axes. | |
| WrapperModule | GetAxisLetter (axis) |
| Get the single-letter G-code identifier for a Mach4 axis ID. | |
| WrapperModule | GetAxisName (axis) |
| Get the human-readable name string for a Mach4 axis ID. | |
| WrapperModule | GetG68PatchGcode (inst) |
| Get a G-code string to re-establish the current axis positions after G68 rotation. | |
| WrapperModule | GetGCodeToCurrentPosition (inst) |
| Build a G-code string with all enabled axis positions at the current location. | |
| WrapperModule | GetGoToPositionGcode (GoToMoveTypeName, MoveOrderName, GcodeHeader, inst) |
| Build a complete G-code block for a named GoTo position move. | |
| WrapperModule | GetConfiguredGoToPositionGcode_ToolChange (inst) |
| Generate a G-code string for the configured Tool Change GoTo position. | |
| WrapperModule | GetConfiguredGoToPosition_ToolChange (inst) |
| Retrieve the Tool Change GoTo position configuration table if one is configured. | |
| WrapperModule | DoesExistGoToPosition_ToolChange (inst) |
| Check whether a Tool Change GoTo position has been configured. | |
| WrapperModule | GetConfiguredGoToPositionGcode_ToolSetter (inst) |
| Generate a G-code string for the configured Tool Setter GoTo position. | |
| WrapperModule | GetConfiguredGoToPosition_ToolSetter (inst) |
| Retrieve the Tool Setter GoTo position configuration table if one is configured. | |
| WrapperModule | DoesExistGoToPosition_ToolSetter (inst) |
| Check whether a Tool Setter GoTo position has been configured. | |
| WrapperModule | GetConfiguredGoToPositionGcode_PartZero (inst) |
| Generate a G-code string for the configured Part Zero GoTo position. | |
| WrapperModule | GetConfiguredGoToPosition_PartZero (inst) |
| Retrieve the Part Zero GoTo position configuration table if one is configured. | |
| WrapperModule | DoesExistGoToPosition_PartZero (inst) |
| Check whether a Part Zero GoTo position has been configured. | |
| WrapperModule | GetConfiguredGoToPositionGcode_MachineZero (inst) |
| Generate a G-code string for the configured Machine Zero GoTo position. | |
| WrapperModule | GetConfiguredGoToPosition_MachineZero (inst) |
| Retrieve the Machine Zero GoTo position configuration table if one is configured. | |
| WrapperModule | DoesExistGoToPosition_MachineZero (inst) |
| Check whether a Machine Zero GoTo position has been configured. | |
| WrapperModule | GetConfiguredGoToPositionGcode_Park (inst) |
| Generate a G-code string for the configured Park GoTo position. | |
| WrapperModule | GetConfiguredGoToPosition_Park (inst) |
| Retrieve the Park GoTo position configuration table if one is configured. | |
| WrapperModule | DoesExistGoToPosition_Park (inst) |
| Check whether a Park GoTo position has been configured. | |
| WrapperModule | GetGoToPositionConfigurationFromSection (section, inst) |
| Read all GoTo position configuration values from a named profile section. | |
| WrapperModule | GetGoToPositionConfigurationFromIndex (idx, inst) |
| Get the GoTo position configuration table by zero-based index. | |
| WrapperModule | GetGoToPositionConfigurationFromName (position_name, inst) |
| Get the GoTo position configuration table by position name. | |
| WrapperModule | IsAtGoToPositionFromName (position_name, inst) |
| Check whether all axes are at the named GoTo position within tolerance. | |
| WrapperModule | GetConfiguredGoToPositions (inst) |
| Get the full configuration table for all configured GoTo positions. | |
| WrapperModule | GetConfiguredGoToPositionNames (inst) |
| Get an ordered list of all configured GoTo position names. | |
| WrapperModule | GetGoToPositionGcodeFromName (position_name, inst) |
| Generate a G-code string for a named GoTo position. | |
| WrapperModule | GetGoToPositionGcodeFromTable (position_table, inst) |
| Generate a G-code string for a multi-step GoTo position move from a position table. | |
| WrapperModule | GetGCodeErrorDescription (ErrorNumber) |
| Get a human-readable description for a G-code interpreter error number. | |
| WrapperModule | Distribute (data) |
| Distribute a number of objects evenly across a one-dimensional space. | |
| WrapperModule | GetMachineType (inst) |
| Get the current machine type and control mode information. | |
| WrapperModule | SetToolTableUserValue_Screen (value, field_name, tool_number,...) |
| Set a numeric user field value in the tool table from a screen chunk context. | |
| WrapperModule | SetToolTableUserValue (fieldName, val, tool, inst) |
| Set a numeric user field value in the tool table for a specified tool. | |
| WrapperModule | GetToolTableUserValue (fieldName, tool, inst) |
| Get a numeric user field value from the tool table for a specified tool. | |
| WrapperModule | SetToolTableUserValueString (fieldName, val, tool, inst) |
| Set a string user field value in the tool table for a specified tool. | |
| WrapperModule | GetToolTableUserValueString (fieldName, tool, inst) |
| Get a string user field value from the tool table for a specified tool. | |
| WrapperModule | AddToolTableUserFieldList (field_list, inst) |
| Add multiple user field definitions to the tool table file. | |
| WrapperModule | IsToolTableUserFieldList (field_list, inst) |
| Check whether all field names in a list exist in the tool table file. | |
| WrapperModule | IsToolTableUserField (fieldName, inst) |
| Check whether a single user field name exists in the tool table file. | |
| WrapperModule | IsToolTableInitialized (inst) |
| Check whether the tool table file has been initialized with a valid structure. | |
| WrapperModule | AddToolTableUserField (FieldName, Description, FieldType, inst) |
| Add a user field definition to the tool table file. | |
| WrapperModule | AddToolTableSimField (FieldName, Description, FieldType, inst) |
| Add a simulation field definition to the tool table file. | |
| WrapperModule | GetToolTableFileName (inst) |
| Get the full file path to the active tool table file. | |
| WrapperModule | IsToolDrillTool (tool, inst) |
| Check whether the specified tool number belongs to a configured drill bank. | |
| WrapperModule | GetAxisIsMovingPositive (axis, inst) |
| Check whether the specified axis is currently moving in the positive direction. | |
| WrapperModule | GetAxisIsMovingNegative (axis, inst) |
| Check whether the specified axis is currently moving in the negative direction. | |
| WrapperModule | GetAxisIsNotMoving (axis, inst) |
| Check whether the specified axis is stationary (not moving in either direction). | |
| WrapperModule | GetAxisIsMoving (axis, inst) |
| Check whether the specified axis is currently moving in either direction. | |
| WrapperModule Jogger | New (axis, inst) |
| Create a new Jogger instance for the specified axis. | |
| WrapperModule Jogger | UseRapidOV () |
| Enable rapid rate override (RRO) scaling for this Jogger instance. | |
| WrapperModule Jogger | CalculateFeedrate () |
| Calculate the effective feedrate applying rapid override if enabled. | |
| WrapperModule Jogger | UpdateFeedrate () |
| Update the active jog feedrate if rapid override is enabled. | |
| WrapperModule Jogger | SetFeedrate () |
| Set the commanded feedrate for this Jogger instance. | |
| WrapperModule Jogger | JogBasedOnMode () |
| Jog the axis using the current external jog mode and configuration parameters. | |
| WrapperModule Jogger | JogVelocity (rate) |
| Jog the axis continuously at a specified rate in the given direction. | |
| WrapperModule Jogger | JogStop () |
| Stop the axis velocity jog immediately. | |
| WrapperModule Jogger | JogIncremental (increment) |
| Jog the axis by a specified increment in the given direction. | |
| WrapperModule Jogger | JogABS (feedrate) |
| Jog the axis to an absolute machine position at the specified feedrate. | |
| WrapperModule Jogger | JogABSWait (feedrate) |
| Jog the axis to an absolute position and block until the move is complete. | |
| WrapperModule Jogger | JogRotaryFeedrate (feedrate) |
| Jog the axis continuously at a feedrate in the specified direction. | |
| WrapperModule Jogger | Wait () |
| Block execution until the axis jog is complete. | |
| WrapperModule Jogger | Stop () |
| Stop the axis jog using the appropriate stop command for the current jog mode. | |
| WrapperModule Jogger | StopWait () |
| Stop the axis jog and wait until motion has fully ceased. | |
| WrapperModule Jogger | IsJogging () |
| Check whether the axis is currently jogging or in the process of stopping. | |
| WrapperModule Jogger | SetJogModeIncremental () |
| Set this Jogger to incremental jog mode. | |
| WrapperModule Jogger | IsJogModeIncremental () |
| Check whether this Jogger is in incremental jog mode. | |
| WrapperModule Jogger | SetJogModeContinuous () |
| Set this Jogger to continuous jog mode. | |
| WrapperModule Jogger | IsJogModeContinuous () |
| Check whether this Jogger is in continuous jog mode. | |
| WrapperModule Jogger | SetJogModeABS () |
| Set this Jogger to ABS (absolute position) jog mode. | |
| WrapperModule Jogger | IsJogModeABS () |
| Check whether this Jogger is in ABS (absolute position) jog mode. | |
| WrapperModule Jogger | SetJogModeFeedrate () |
| Set this Jogger to feedrate jog mode. | |
| WrapperModule Jogger | IsJogModeFeedrate () |
| Check whether this Jogger is in feedrate jog mode. | |
| WrapperModule Jogger | GetJogMode () |
| Get the current jog mode of this Jogger instance. | |
| WrapperModule Averager | new (num_points) |
| Create a new Averager instance with the specified sample window size. | |
| WrapperModule Averager | sample (value_op) |
| Add a sampled value to the window and return a summary statistic. | |
| WrapperModule Averager | mean () |
| Calculate the arithmetic mean of all sampled y-values in the current window. | |
| WrapperModule Averager | variance () |
| Calculate the variance of the sampled y-values in the current window. | |
| WrapperModule Averager | stdev () |
| Calculate the standard deviation of the sampled y-values. | |
| WrapperModule Averager | covariance (mean_value) |
| Calculate the covariance between x-index positions and sampled y-values. | |
| WrapperModule Averager | mean_x () |
| Calculate the mean of the x-index sequence for the current sample window. | |
| WrapperModule Averager | stdev_x () |
| Calculate the standard deviation of the x-index sequence for the current sample window. | |
| WrapperModule Averager | variance_x () |
| Calculate the variance of the x-index sequence for the current sample window. | |
| WrapperModule Averager | trend () |
| Calculate the trend line value using least squares linear regression. | |
| WrapperModule | CreateOEMGCodes (GCodeRangeString) |
| Create OEM G-code substitution entries in the Mach4 profile if enabled. | |
| WrapperModule | ElapsedTime (from_ll, to_ll) |
| Calculate elapsed time in milliseconds between two wxLongLong timestamps. | |
| WrapperModule | FlushProfile () |
| Flush the Mach4 profile to disk. | |
| WrapperModule | GetRecentMachDir () |
| Get the most recently used Mach4 directory from MachMotion.ini. | |
| WrapperModule | GetAppDataRoaming () |
| Get the Windows roaming AppData directory path with fallback methods. | |
| WrapperModule | GetAppDataRoaming_Method1 () |
| Get the Windows roaming AppData directory path using the Windows Shell API. | |
| WrapperModule | GetAppDataRoaming_Method2 () |
| Get the Windows roaming AppData directory path using the APPDATA environment variable. | |
| WrapperModule FunctionQueue | Create () |
| Create a new FunctionQueue instance with the given name. | |
| itself (name will be auto-discovered) | |
| Register a named function in this FunctionQueue group. | |
| WrapperModule FunctionQueue | Register (func) |
| Register a named function in this FunctionQueue group. | |
| WrapperModule FunctionQueue | Execute () |
| Execute all registered functions in this FunctionQueue group. | |
| WrapperModule FunctionQueue | Print () |
| Log all registered functions in this FunctionQueue group to the Mach log. | |
| WrapperModule | parseISO8601Timestamp (str) |
| parse a timestamp formatted as an ISO8601 string. | |
| WrapperModule __private zerobrane | BuildAPI (t, seen) |
| Build a ZeroBrane Studio API table structure from a Lua table. | |
| WrapperModule __private zerobrane | PopulateAPI (object, namespace, id) |
| Populate a ZeroBrane Studio API file with data from the specified object and namespace. | |
| WrapperModule | CopyToClipboard (data) |
| WrapperModule | execute (command, window_style, wait_on_return) |
| WrapperModule | OpenURL (url) |
| Open a URL in the default system browser or application. | |
| open_cmd (url) | |
| Open a URL using the macOS 'open' command. | |
| WrapperModule | SpindleSpeedVariation (on_off, inst) |
| Enable or disable Spindle Speed Variation (SSV). | |
| WrapperModule | SpindleSpeedVariationToggle () |
| Toggle Spindle Speed Variation (SSV) between on and off states. | |
| WrapperModule | IsSpindleSpeedVariationOn () |
| Check whether Spindle Speed Variation (SSV) is currently enabled. | |
| WrapperModule | IsLuaRunningInScreenChunk () |
| Check whether the current Lua execution context is a screen chunk. | |
| WrapperModule | IsLuaRunningInMCodeChunk () |
| Check whether the current Lua execution context is an M-code chunk. | |
| WrapperModule | IsEditorActive () |
| Check whether Mach4 is currently running in the editor. | |
| WrapperModule | IsMachShuttingDown () |
| Check whether Mach4 is currently in the process of shutting down. | |
| WrapperModule | AppendActiveDialog (dlg_name, dlg) |
| Register a dialog in the active dialogs tracking table. | |
| WrapperModule | RemoveActiveDialog (dlg_name) |
| Remove a dialog from the active dialogs registry. | |
| WrapperModule | CloseActiveDialogs () |
| Close all active dialogs that have been registered. | |
| f (x) | |
| Return a function that calculates y-values for a parabola passing through three given points. | |
| WrapperModule geom | GenericParabola (x0, y0, x1, y1, x2, y2) |
| Return a function that calculates y-values for a parabola passing through three given points. | |
| WrapperModule geom | Parabola (x0, x1, y_max) |
| Return a function that calculates y-values for a parameter described by the specified geometry. | |
| WrapperModule | NewSerialConnection (portnumber, setup, error_codes) |
| Create and configure a new serial port connection wrapper. | |
| wrapper | write (self, stringdata, timeout) |
| Write a string to the serial port. | |
| wrapper | writeBcc (self, stringdata, timeout) |
| Write a BCC-checksummed string to the serial port. | |
| wrapper | read (self, read_len, timeout) |
| Read data from the serial port. | |
| wrapper | request (self, request_cmd, read_len, timeout) |
| Write a command string and read back a response. | |
| wrapper | requestBcc (self, request_cmd, read_len, timeout) |
| Write a BCC-checksummed command and read back a response. | |
| wrapper | close (self) |
| Close the serial port connection. | |
| wrapper | bccCheckSum (self, str) |
| Calculate the BCC checksum for a string and return the checksum character and the concatenated result. | |
| WrapperModule AddLine | ( | Table | , |
| WriteString | ) |
Append a string as a new line to a table used for file writing.
Ensures the WriteString ends with a newline character if it does not already contain one. Converts non-string values to strings via tostring(). Returns an error if Table is nil.
| Table | (table) The array table to append the line into |
| WriteString | (string|any) The string (or value convertible to string) to append as a new line |
| WrapperModule AddOEMParamSignalToOutputIgnoreList | ( | src_oemparamsig | , |
| target_lists | , | ||
| inst | ) |
Add an OEM parameter output signal to one or more output ignore lists if it is a valid general output.
Checks whether the OEM parameter specified by src_oemparamsig is mapped via w.IsOEMParamSigMapped(). If mapped, retrieves the IOSig object via w.GetOEMParamIOSigObject() and verifies it is an output signal. If the signal ID is in w.OUTPUT_NUMBERS (a general output), delegates to w.AddOutputToOutputIgnoreLists(); otherwise calls w.AddOutputToOutputIgnoreLists() directly with the signal ID. Does nothing if the parameter is not mapped or not an output signal.
| src_oemparamsig | (string) The OEM parameter name whose value is an encoded output signal |
| target_lists | (table) Array of OEM parameter name strings identifying the ignore lists to update |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule AddOutputToAllOutputIgnoreLists | ( | sig_id | , |
| inst | ) |
Add a general output signal to all standard output ignore lists for all Mach4 instances.
Convenience wrapper that calls w.AddOutputToOutputIgnoreLists() with the standard set of three OEM parameter lists: 'IgnoreOutputsOnDisable', 'IgnoreOutputsOnStop', and 'IgnoreOutputsOnEmergencyStop'. The sig_id must be a valid mc.OSIG_OUTPUT* signal.
| sig_id | (number) The output signal ID (one of mc.OSIG_OUTPUT*) to add to all ignore lists |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule AddOutputToOutputIgnoreLists | ( | sig_id | , |
| target_lists | , | ||
| inst | ) |
Add an output signal number to one or more OEM parameter output ignore lists.
Validates that sig_id is a known general output signal via w.OUTPUT_NUMBERS. For each OEM parameter name in target_lists, reads the current delimited list of output numbers via w.GetOEMParamValueString(), checks whether the output number is already present, and if not, inserts it, sorts the list, and writes it back via w.SetOEMParamValueString(). Logs an error if a parameter cannot be read.
| sig_id | (number) The output signal ID (one of mc.OSIG_OUTPUT*) to add to the ignore lists |
| target_lists | (table) Array of OEM parameter name strings identifying the lists to update (e.g., {"IgnoreOutputsOnDisable", "IgnoreOutputsOnStop"}) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule debug AddToFunctionNameMap | ( | tables | ) |
Add function-to-name mappings to the cache without clearing existing entries.
Delegates to w.debug.UpdateFunctionNameMap() with dont_clear_cache set to true, so that new table entries are merged into the existing function name cache rather than replacing it.
| tables | (table) Table mapping display names to module tables to scan for functions |
| WrapperModule AddToListHistory | ( | filename | , |
| list_line | ) |
Append a new line to a list history file, maintaining a maximum of 200 entries.
Reads the existing history via w.ReadListHistory(), then appends the new line (with newlines escaped as
) to the file only if it differs from the last saved entry. If the file grows beyond 200 lines, rewrites it retaining only the most recent 200 entries.
| filename | (string) Full path to the history file to append to |
| list_line | (string) The line to append. Newline characters are escaped before writing |
| WrapperModule AddToolTableSimField | ( | FieldName | , |
| Description | , | ||
| FieldType | , | ||
| inst | ) |
Add a simulation field definition to the tool table file.
Saves the current in-memory tool table to disk, then reads the tool table INI file to check whether a simulation field with the given name already exists. If it does not exist, adds the new field definition (name, description, and type) and increments the SimFields count. Reloads the tool table into memory after writing. Does nothing and returns silently if the field already exists.
| FieldName | (string) The internal key name for the simulation field (e.g., "SpindleRotation") |
| Description | (string) The human-readable description shown in the tool table UI |
| FieldType | (string) The field type specification string (e.g., "Choice(Any=0,FWD=1,REV=2)") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule AddToolTableUserField | ( | FieldName | , |
| Description | , | ||
| FieldType | , | ||
| inst | ) |
Add a user field definition to the tool table file.
Saves the current in-memory tool table to disk, then reads the tool table INI file to check whether a user field with the given name already exists. If it does not exist, adds the new field definition (name, description, and type) and increments the UsrFields count. Reloads the tool table into memory after writing. Does nothing and returns silently if the field already exists.
| FieldName | (string) The internal key name for the user field (e.g., "SpindleRotation") |
| Description | (string) The human-readable description shown in the tool table UI |
| FieldType | (string) The field type specification string (e.g., "Choice(Any=0,FWD Rotation=1,REV Rotation=2,No Rotation=3)") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule AddToolTableUserFieldList | ( | field_list | , |
| inst | ) |
Add multiple user field definitions to the tool table file.
Saves the current in-memory tool table to disk, opens the tool table INI file, and for each entry in field_list checks whether a user field with that name already exists. New fields are added with their name, description, and type, and the UsrFields count is incremented accordingly. After writing, the tool table is reloaded into memory. Fields that already exist are silently skipped.
| field_list | (table) A table whose keys are field names and values are tables with keys:
|
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule AlarmError | ( | obj | , |
| FileName | , | ||
| Line | , | ||
| ForceAlarm | ) |
Construct and invoke a GMS alarm from obj.
WrapperModule.AlarmError
| obj | a string or object created by w.Error() (i.e. it's safe to use with nearly anything) |
| WrapperModule AlarmMessage | ( | Message | , |
| FileName | , | ||
| Line | , | ||
| ForceAlarm | ) |
Invoke a GMS alarm message with protected error handling.
Wraps w._AlarmMessage() in a w.pcall() to safely deliver an alarm message. If the call fails, logs the error via w.Log() rather than propagating the exception. This is the public-facing variant that accepts a plain string message rather than an error object.
| Message | (string|table) The alarm message string or a GMS message table with 'Class' and related fields |
| FileName | (string|nil) The source filename where the alarm originated. If nil, uses empty string |
| Line | (number|nil) The source line number where the alarm originated. If nil, uses 0 |
| ForceAlarm | (boolean|nil) If true, forces the alarm even if the machine is already disabled |
Referenced by eWaitForOEMParamSig(), WaitForIoState(), WaitForOEMParamSig(), WaitForRegisterValue(), and WaitForSignal().
| WrapperModule api | ( | ... | ) |
Call a Mach4 API function by name with automatic error handling (no metadata).
Convenience wrapper around w.api_e() that passes nil as the metadata argument, disabling support for allowable error codes. Accepts the API function name and its arguments as variadic parameters and delegates to WrapperModule.api_e(nil, ...).
| ... | (any) The API function name (string) followed by all arguments to pass to the API function |
| WrapperModule api_e | ( | meta | , |
| api_func | , | ||
| ... ) |
Call a Mach4 API function by name with automatic error handling and optional error metadata.
Looks up the named function in the mc namespace, calls it via w.pcall(), and inspects the result for both Lua errors and Mach4 error return codes. If the call raises a Lua error, raises it via w.Error(). If the last return value is a non-zero Mach4 error code and is not in the meta.Ignore list, raises a formatted error via w.Error(). On success, returns all non-error return values (i.e., all return values except the final error code).
| meta | (table|nil) Optional metadata table with key: 'Ignore' (table of mc error codes to allow without raising an error) |
| api_func | (string) The name of the Mach4 API function to call (must exist in the mc namespace) |
| ... | (any) Arguments to pass to the Mach4 API function |
| WrapperModule AppendActiveDialog | ( | dlg_name | , |
| dlg | ) |
Register a dialog in the active dialogs tracking table.
Adds the specified dialog to the ActiveDlgs table under the given name key. Only one dialog instance per name is allowed - if a dialog with the same name already exists in the table, the new one will not be added.
| dlg_name | (string) The name key to register the dialog under |
| dlg | (table) The dialog object to register |
| WrapperModule AppendArgs | ( | suffix_table | , |
| ... ) |
| WrapperModule AppendTables | ( | from | , |
| to | ) |
Append all array elements from one table to the end of another table.
Iterates over the sequential integer keys (1 to #from) of the source table and inserts each value into the destination table using table.insert(). Only sequential array elements are appended; non-sequential or string-keyed entries in 'from' are ignored.
| from | (table) The source array table whose elements are to be appended |
| to | (table) The destination array table to append elements into |
| WrapperModule AppendToFile | ( | logfile | , |
| msg | ) |
Append a message string followed by a newline to a log file.
Opens the specified log file in append mode and writes the message followed by "\n". If logfile is nil, defaults to 'wrapper.log'. Silently does nothing if the file cannot be opened.
| logfile | (string|nil) Path to the log file. Defaults to 'wrapper.log' if nil |
| msg | (string) The message to append to the file |
| WrapperModule ApplyMotorMappingsToMotionController | ( | inst | ) |
Apply current motor mappings to the motion controller plugin.
Delegates to m.MotionController[w.GetUTI(inst)]:UpdateMotorMapping() to instruct the motion controller plugin to re-read the motor configuration and apply any changes. Call this after modifying motor-to-axis mappings via MapMotorsToAxis() or UnMapMotorsFromAxis().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| wrapper bccCheckSum | ( | self | , |
| str | ) |
Calculate the BCC checksum for a string and return the checksum character and the concatenated result.
Computes a Block Check Character (BCC) checksum by XORing all bytes of the input string together. Returns both the checksum character alone and the original string with the checksum appended. This is used for serial communication protocols that require BCC error detection.
| str | (string) The data string to compute the checksum for |
| WrapperModule BoolToNumber | ( | value | ) |
Convert a boolean value to its numeric equivalent (1 or 0).
| value | (boolean) The boolean value to convert |
| math bound | ( | val | , |
| minimum | , | ||
| maximum | ) |
Clamp a value to within a specified minimum and maximum range.
Returns the value clamped to [minimum, maximum] using math.min and math.max. Equivalent to math.min(maximum, math.max(minimum, val)).
| val | (number) The value to clamp |
| minimum | (number) The lower bound of the range |
| maximum | (number) The upper bound of the range |
| WrapperModule debug BriefParameterList | ( | stack_frame | ) |
Return a comma-delimited string of parameter name(value) pairs for a stack frame.
Calls w.debug.GetParameters() with stack_frame+1 to skip this function's own frame, then sorts the results by parameter position and formats them as "name(stringvalue), ..." in declaration order. Returns an empty string if there are no parameters.
| stack_frame | (number) The stack frame to inspect, relative to the caller of this function |
| WrapperModule __private zerobrane BuildAPI | ( | t | , |
| seen | ) |
Build a ZeroBrane Studio API table structure from a Lua table.
Recursively converts a Lua table of functions and values into the ZeroBrane Studio API format (lib/function/value entries with type, description, childs, etc.). Handles cyclic table references by tracking seen tables and leaving their childs empty. Keys starting with '__' are skipped. Tables with a '_DESCRIPTION' key will use it as the description.
| t | (table) The Lua table to convert into API format |
| seen | (table|nil) Internal recursion guard table tracking already-processed tables. Pass nil on initial call |
| WrapperModule CalculateCarouselAngularDistances | ( | from_deg | , |
| to_deg | ) |
Calculate the clockwise and counter-clockwise angular distances between two positions on a 360-degree carousel.
Normalizes both from_deg and to_deg to the range [0, 360) using modulo arithmetic, then computes the clockwise distance (positive rotation) and counter-clockwise distance (negative rotation) as the two complementary arc lengths between the positions.
| from_deg | (number) The starting angle in degrees (will be normalized to 0-360) |
| to_deg | (number) The target angle in degrees (will be normalized to 0-360) |
| WrapperModule CalculateCarouselPathScore | ( | distance_deg | , |
| final_cumulative_deg | , | ||
| current_cumulative_deg | ) |
Calculate a weighted score for a carousel rotation path (lower score is better).
Combines a distance score (absolute movement in degrees) and a deviation score (absolute final cumulative position) using dynamically adjusted weights based on how close the current cumulative position is to the rotation limits. Below 70% of the usable limit, almost exclusively favors shortest path (99% distance, 1% deviation). Above 70%, uses an exponential transition toward deviation-priority weights (5% distance, 95% deviation) to avoid hitting the mechanical stops.
| distance_deg | (number) The absolute angular distance of the proposed movement in degrees |
| final_cumulative_deg | (number) The cumulative rotation after the movement in degrees |
| current_cumulative_deg | (number) The current cumulative rotation in degrees (used to determine proximity to limits) |
| WrapperModule Jogger CalculateFeedrate | ( | ) |
Calculate the effective feedrate applying rapid override if enabled.
If use_rapid_ov is true, reads the current rapid rate override (RRO) percentage via mcCntlGetRRO and scales cmd_feedrate accordingly. The resulting feedrate is then clamped to the configured max_rate and min_rate limits. If rapid override is not active, only the clamp is applied.
| WrapperModule CalculateTotalAppliedOffset | ( | axis_id | , |
| ToUnits | ) |
Calculate the total coordinate offset applied to an axis, in the specified unit system.
Uses the fundamental relationship X(G53) - X(G54) = Offset_X(G54) to compute the total offset. Reads the machine position via mc.mcAxisGetMachinePos() (in setup units) and the current absolute part position via mc.mcCntlGetPoundVar() (SV_CURRENT_ABS_X + axis_id, also in setup units), subtracts them to get the offset in setup units, then converts to ToUnits via ConvertFromSetupUnits(). If ToUnits is nil, returns the value in setup units.
| axis_id | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| ToUnits | (number|nil) The unit system for the returned value: 200 for imperial, 210 for metric. Defaults to setup units if nil |
| UI CancelPleaseWaitDialog | ( | ) |
Handle user cancellation of the PleaseWait dialog, performing context-appropriate cleanup.
Sets the EventCloseWindow flag to true, then dispatches to the appropriate cancel behavior based on WaitType. MachState cancellation disables the machine via w.SetMachEnable(false). MachState_CycleStopOnCancel sends a cycle stop via mc.mcCntlCycleStop(). DryRun cancellation additionally resets the controller via mc.mcCntlReset(). All other wait types simply close the dialog. Always calls UI.ClosePleaseWaitDialog() to end the modal session.
| WrapperModule DbgCheckPoint CHECK | ( | descr | , |
| value | ) |
Record a checkpoint with an optional description and value.
Updates the recency tracking via update_recent(), then creates or updates the checkpoint entry for the given id. If value is nil, increments the stored counter by 1. If value is provided, stores it directly. The description string is stored as the message for this checkpoint.
| id | (any) The checkpoint identifier (typically a string label like "Start" or "Step1") |
| descr | (string|nil) A description of the current state at this checkpoint |
| value | (any|nil) An explicit value to store. If nil, the internal counter is incremented |
| WrapperModule CheckIfLicensed | ( | inst | , |
| feature_name | ) |
Check whether a named feature is licensed in the Mach4 license file.
Reads the Mach license file at <MachDirectory>\Licenses\MachLic.dat and checks whether the specified feature is authorized via mc.mcCntlCheckLicenseFeature(). Returns true if the feature is licensed (rc == mc.MERROR_NOERROR), false otherwise. This is the updated license checker for MachMotion 2025 that reads from the Mach license rather than the plugin.
| inst | (number|nil) The Mach4 instance handle. If nil, uses current instance |
| feature_name | (string|nil) The feature name to check. If nil, returns false |
| WrapperModule CheckStopStatus | ( | Filename | , |
| LineNumber | , | ||
| inst | ) |
Check whether the machine stop/disable status has changed since it was last recorded.
Compares the current CmdStopAndDisable register value against the previously saved value in mm_StopStatus. If the values differ, the machine has been disabled since the last call to w.SetStopStatus(). In debugging mode, also tracks file and line number information and a loop iteration counter via OEM registers for step-through debugging support.
| Filename | (string) The source filename to record in debugging mode |
| LineNumber | (number) The source line number to record in debugging mode |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| UI clean_up | ( | ) |
Clean up the tool path regeneration dialog timer and close the dialog.
Stops and clears the wx.wxTimer (UI.dlg_timer) if it is running, rewinds the loaded G-code file via mc.mcCntlRewindFile() to handle files that finish inside subroutines, and closes the tool path regeneration dialog via w.Formatting.CloseDialog(). This is a local closure defined inside WrapperModule.RegenerateToolPathDialog().
| WrapperModule CleanUserCommandName | ( | command_name | ) |
Sanitize a user command name by removing special characters.
Strips the following characters from command_name: backslash, period, single quote, left bracket, and right bracket. Used to produce safe register and I/O names from arbitrary command name strings.
| command_name | (string) The raw command name to sanitize |
| WrapperModule ClearOEMParamValueBit | ( | ParamName | , |
| BitIdx | , | ||
| inst | ) |
Clear a specific bit in an OEM parameter value.
Convenience wrapper that calls w.SetOEMParamValueBit() with state set to false, effectively clearing the bit at position BitIdx in the OEM parameter identified by ParamName.
| ParamName | (string) The name of the OEM parameter whose bit is to be cleared |
| BitIdx | (number) The zero-indexed bit position to clear |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ClearOEMRegValueBit | ( | RegName | , |
| BitIdx | , | ||
| inst | ) |
Clear a specific bit in an OEM register value.
Convenience wrapper that calls w.SetOEMRegValueBit() with state set to false, effectively clearing the bit at position BitIdx in the OEM register identified by RegName.
| RegName | (string) The name of the OEM register whose bit is to be cleared |
| BitIdx | (number) The zero-indexed bit position to clear |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ClearProbeFeedbackPositions | ( | ) |
Reset all probe feedback position OEM parameters to the Mach4 nil pound variable value.
Reads the nil pound variable via mc.mcCntlGetPoundVar(inst, 0), then iterates through position indices 0 through 5 and writes the nil pound value to each "ProbeFeedbackPosition_{i}" OEM parameter via w.SetOEMParamValue(). Raises an error via w.Error() if any write fails.
| WrapperModule ClearValueBit | ( | value | , |
| BitIdx | ) |
Clear the bit at a zero-indexed position in a value.
Convenience wrapper that calls w.SetValueBit() with state set to false, effectively clearing the bit at position BitIdx in the given value.
| value | (number) The integer value whose bit is to be cleared |
| BitIdx | (number) The zero-indexed bit position to clear (must be in [0, MAX_BITS)) |
| wrapper close | ( | self | ) |
Close the serial port connection.
Closes the serial port associated with this connection wrapper. If the port cannot be closed, raises an error via w.Error(). Logs the close operation on success.
| WrapperModule CloseActiveDialogs | ( | ) |
Close all active dialogs that have been registered.
Iterates through the ActiveDlgs table and calls _end_modal(wx.wxID_CANCEL) on each registered dialog, effectively closing all open dialogs. Logs each dialog being closed.
| WrapperModule CloseGMSMessage | ( | Handle | ) |
Close a GMS alert caused by a message from CreateSystemGlobalMessage.
Sends a "CloseMonitor" command to the GMS plugin via w.SendGMSCommand() with the specified handle. The handle must be a valid numeric value previously returned by w.CreateSystemGlobalMessage(). Returns an error if the handle is invalid.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| WrapperModule CloseGMSNotification | ( | Handle | ) |
Close a GMS notice or notification created by CreateGMSDialog or CreateGMSNotification.
Sends a "CloseNotice" command to the GMS plugin via w.SendGMSCommand() with the specified handle. The handle must be a valid numeric value previously returned by w.CreateGMSDialog() or w.CreateGMSNotification(). Returns an error if the handle is invalid.
| Handle | (number|string) The GMS notice handle returned by w.CreateGMSDialog() or w.CreateGMSNotification() |
| UI ClosePleaseWaitDialog | ( | ) |
Close the PleaseWait dialog by delegating to _ClosePleaseWaitDialog() with error handling.
Wraps UI._ClosePleaseWaitDialog() in a w.pcall() protected call. If an error occurs, logs the error via w.FunctionError() and displays it via w.wxMessageBox(). Returns the result of _ClosePleaseWaitDialog() on success, or false on error.
| EndModalCode | (number|nil) The modal result code to pass to MainPleaseWaitDialog:EndModal(). Defaults to 0 |
| UI ClosePleaseWaitDialog | ( | EndModalCode | ) |
Enforce a minimum display time then end the PleaseWait dialog modal session.
Waits until at least MinimumTime milliseconds have elapsed since the dialog was opened (to prevent modal state issues when conditions are met very quickly), then calls MainPleaseWaitDialog:EndModal(EndModalCode) and stops and clears the timer.
| EndModalCode | (number|nil) The modal result code. Defaults to 0 if nil |
| WrapperModule table concat | ( | tbl | , |
| sep | , | ||
| i | , | ||
| j | ) |
Concatenate all elements of a table into a string, coercing non-string values via tostring().
Replacement for the standard table.concat() which fails on boolean, table, or other non-string/number values. Converts every element to a string with tostring() before concatenating.
| tbl | (table) The table whose elements to concatenate |
| sep | (string|nil) The separator string inserted between elements |
| i | (number|nil) The starting index. Defaults to 1 if nil |
| j | (number|nil) The ending index. Defaults to #tbl if nil |
| WrapperModule ConfigureToolSpecificSoftLimits | ( | current_tool | , |
| inst | ) |
Apply tool-specific soft limit values from the tool table to active machine axes.
Checks whether tool-specific soft limits are enabled via the ToolSpecificSoftLimitsEnabled OEM parameter. If enabled and the tool table is initialized, reads per-tool soft limit values (SoftLimitMaxX, SoftLimitMinX, etc.) from user-defined tool table fields for the current tool. For each enabled axis (X through C), if a tool-specific soft limit value exists and ToolSoftLimitEnabled is set for the current tool, applies the value via mc.mcAxisSetSoftlimitMax/Min. Otherwise, restores the profile-defined soft limit if the current value has drifted. Sets a Mach last error message if any tool-specific limits are applied.
| current_tool | (number) The tool number whose soft limit values should be applied |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
Requires user-defined tool table fields named "SoftLimitMax{Axis}" and "SoftLimitMin{Axis}" (e.g., "SoftLimitMaxX", "SoftLimitMinZ") and a "ToolSoftLimitEnabled" choice field to be present. Missing fields are automatically added to the tool table on first use.
| WrapperModule ConvertFromCurrentUnits | ( | value | , |
| ToUnits | ) |
Convert a value from current units to the specified unit system (typically setup units).
Reads the current active unit system and converts the given value to ToUnits. If ToUnits is not specified, defaults to the machine setup units. Converts metric-to-imperial (multiply by 25.4) or imperial-to-metric (divide by 25.4) as needed. If FromUnits equals ToUnits, the value is returned unchanged. This is the inverse of ConvertFromSetupUnits().
| value | (number) The value in current units to convert |
| ToUnits | (number|nil) The target unit system: 200 for imperial, 210 for metric. Defaults to setup units if nil |
| WrapperModule ConvertFromImperialToCurrentUnits | ( | value | ) |
Convert a value from imperial units to the current unit system.
If the current unit system is metric (210), multiplies the value by 25.4 to convert from inches to millimeters. If the current unit system is already imperial, the value is returned unchanged. Caches the current unit system in the global MACHINE_CURRENT_UNITS.
| value | (number) The value in imperial (inches) to convert |
| WrapperModule ConvertFromMetricToCurrentUnits | ( | value | ) |
Convert a value from metric units to the current unit system.
If the current unit system is imperial (200), divides the value by 25.4 to convert from millimeters to inches. If the current unit system is already metric, the value is returned unchanged. Caches the current unit system in the global MACHINE_CURRENT_UNITS.
| value | (number) The value in metric (millimeters) to convert |
| WrapperModule ConvertFromSetupUnits | ( | value | , |
| ToUnits | ) |
Convert a value from setup units to the specified unit system (typically current units).
Reads the machine setup units and converts the given value to ToUnits. If ToUnits is not specified, defaults to the currently active unit system via mc.mcCntlGetUnitsCurrent(). Converts imperial-to-metric (multiply by 25.4) or metric-to-imperial (divide by 25.4) as needed. If FromUnits equals ToUnits, the value is returned unchanged.
| value | (number) The value in setup units to convert |
| ToUnits | (number|nil) The target unit system: 200 for imperial, 210 for metric. Defaults to current units if nil |
| WrapperModule ConvertMachinePositionToPartPosition | ( | axis | , |
| machineposition | , | ||
| UnitSystem | ) |
Convert a machine-coordinate position to a part-coordinate position.
Computes the total applied offset for the specified axis via CalculateTotalAppliedOffset() in the given unit system (or setup units if unspecified), then returns machineposition - offset. Both the input position and the returned position are expressed in UnitSystem units. This is the inverse of ConvertPartPositionToMachinePosition().
| axis | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| machineposition | (number) The machine-coordinate position to convert, expressed in UnitSystem units |
| UnitSystem | (number|nil) The unit system: 200 for imperial, 210 for metric. Defaults to setup units if nil |
| WrapperModule ConvertPartPositionToMachinePosition | ( | axis | , |
| partposition | , | ||
| UnitSystem | ) |
Convert a part-coordinate position to a machine-coordinate position.
Computes the total applied offset for the specified axis via CalculateTotalAppliedOffset() in the given unit system (or setup units if unspecified), then returns partposition + offset. This is the inverse of ConvertMachinePositionToPartPosition().
| axis | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| partposition | (number) The part-coordinate position to convert, expressed in UnitSystem units |
| UnitSystem | (number|nil) The unit system: 200 for imperial, 210 for metric. Defaults to setup units if nil |
| WrapperModule CopyTables | ( | from | , |
| to | ) |
Copy all key-value pairs from one table into another, merging matching keys.
-----------------— END INI WRAPPERS ---------------------— -------------------— START TABLE WRAPPERS ---------------—
Iterates over all keys in the 'from' table. For each key, if a matching key exists in 'to', the value is overwritten. If the key does not exist in 'to', it is inserted. This is a shallow copy; nested tables are not recursively duplicated.
| from | (table) The source table whose entries are to be copied |
| to | (table) The destination table to copy entries into |
| WrapperModule CopyToClipboard | ( | data | ) |
| WrapperModule Averager covariance | ( | mean_value | ) |
Calculate the covariance between x-index positions and sampled y-values.
Computes the covariance as sum((x_i - x_mean)(y_i - y_mean)) / n over the stored sample window. The x-indices represent positions in the sample sequence. Points are stored in reverse order, so x is adjusted accordingly. If mean_x or mean_value are not provided, they are computed internally via mean_x() and mean() respectively.
| mean_x | (number|nil) The mean of the x-index sequence. If nil, computed via mean_x() |
| mean_value | (number|nil) The mean of the sampled y-values. If nil, computed via mean() |
| WrapperModule FunctionQueue Create | ( | ) |
Create a new FunctionQueue instance with the given name.
Instantiates a new FunctionQueue object using setmetatable. The queue starts with an empty functions list. The name is used in log messages to identify the group.
| name | (string|nil) A human-readable name for this function queue group. Defaults to "Unnamed Registrar" if nil |
| WrapperModule CreateCommand | ( | cmd_table | ) |
Register a command table entry in the m.Commands registry.
Adds or replaces the command in m.Commands using the cleaned command name as the key. The command name is sanitized via w.CleanUserCommandName() before storage. Initializes m.Commands as an empty table if it does not already exist. Does nothing if cmd_table.Name is nil.
| cmd_table | (table) The command configuration table. Must include a 'Name' field and typically includes: Action, ActionOption, ActionOptionHandle, FeedbackSourceType, FeedbackSource, FeedbackSourceHandle, FeedbackCheckPeriod, FeedbackTargetType, FeedbackTarget, FeedbackTargetHandle |
Register a pre-canned command action option in the m.CommandActions table.
Initializes m.CommandActions as an empty table if it does not already exist, then stores the provided function under the given name key. Used to register action callbacks that can be referenced by command entries with Action set to "Pre-Canned".
| name | (string) The name key under which to register the action function |
| func | (function) The action function to register |
Register a pre-canned command feedback option in the m.CommandFeedbacks table.
Initializes m.CommandFeedbacks as an empty table if it does not already exist, then stores the provided function under the given name key. Used to register feedback callbacks that return a boolean state and can be referenced by command entries with FeedbackSourceType set to "Pre-Canned".
| name | (string) The name key under which to register the feedback function |
| func | (function) The feedback function to register. Should return a boolean state |
| WrapperModule CreateFunctionFromCommand | ( | command_name | ) |
Create an executable function closure from a named user command.
Looks up the command by name via w.GetUserCommand() and m.Commands. Based on the command's Action field, returns a closure that implements the appropriate behavior:
| command_name | (string) The name of the user command to convert to a function |
| WrapperModule CreateGMSDialog | ( | Table | ) |
Create an independent GMS dialog with title, description, and optional extra content panels.
Sends a "CreateNotice" command to the GMS plugin with all dialog parameters serialized as a pipe-delimited string. At least one of Title, Description, or a non-empty ExtraLines entry must be provided for the dialog to be created. If Title or Description are non-empty, an individual dialog is shown; otherwise the content is added to the notification list. The HideCloseBtn option removes the close button, making the dialog closable only via the returned handle.
| Table | (table) Configuration table with keys:
|
| WrapperModule CreateGMSNotification | ( | Text | , |
| Title | , | ||
| Time | , | ||
| GroupBox | , | ||
| CloseBtn | , | ||
| Size | , | ||
| Red | , | ||
| Green | , | ||
| Blue | ) |
Add a text notification entry to the GMS notification bar.
Sends a "CreateNotification" command to the GMS plugin via w.SendGMSCommand() with all notification parameters formatted as a pipe-delimited string. Either Text or Title must be a non-empty string for the notification to be created. The GroupBox parameter controls whether the text is enclosed in a static group box. The CloseBtn parameter controls whether a dismiss button is shown. RGB values are clamped to the range [0, 255].
| Text | (string|nil) The main body text of the notification. If nil, defaults to "" |
| Title | (string|nil) The title shown on the group box or expandable panel. If nil, defaults to "" |
| Time | (number|nil) Display duration in milliseconds. Use -1 for indefinite. If nil, defaults to -1 |
| GroupBox | (boolean|nil) If true, surrounds the text in a static group box. If nil, defaults to true |
| CloseBtn | (boolean|nil) If true, shows a dismiss button. If nil, defaults to true |
| Size | (number|nil) Font size (-1, -2, -3 for predefined sizes, or a positive value). If nil, defaults to -1 |
| Red | (number|nil) Red component of the text color (0-255). If nil, defaults to 0 |
| Green | (number|nil) Green component of the text color (0-255). If nil, defaults to 0 |
| Blue | (number|nil) Blue component of the text color (0-255). If nil, defaults to 0 |
| WrapperModule CreateInput | ( | dev_name | , |
| io_name | , | ||
| other_info | ) |
Create a dynamic input I/O point via the MachMotion plugin.
Shortcut wrapper around w.CreateIO() that always creates an input (is_input = true). If dev_name is nil, io_name is treated as the I/O name and 'MachMotion' is used as the device.
| dev_name | (string|nil) The device name under which to register the input. If nil, uses 'MachMotion' |
| io_name | (string) The name of the input I/O point to create |
| other_info | (table|nil) Optional configuration table with keys: 'permanent' (boolean), 'type' (string/number), 'description' (string) |
| WrapperModule CreateIO | ( | dev_name | , |
| io_name | , | ||
| is_input | , | ||
| other_info | ) |
Dynamically create an I/O point via the MachMotion plugin.
Creates a new input or output I/O point by sending a CreateInput or CreateOutput command to the MachMotion plugin via the mm_LuaRequest register. If the I/O point already exists, returns the existing handle immediately without creating a duplicate. If dev_name is nil, io_name is used as the I/O name and 'MachMotion' is used as the device. The other_info table controls permanence, type, and description of the created I/O point. Permanent I/O points are recreated by the plugin on every Mach4 startup.
| dev_name | (string|nil) The device name under which to register the I/O. If nil, uses 'MachMotion' |
| io_name | (string) The name of the I/O point to create |
| is_input | (boolean) True to create an input, false to create an output |
| other_info | (table|nil) Optional configuration table with keys:
|
| WrapperModule CreateOEMGCodes | ( | GCodeRangeString | ) |
Create OEM G-code substitution entries in the Mach4 profile if enabled.
Checks the EnableOEMGCodeSubs OEM parameter before proceeding. If enabled, calls _CreateOEMGCodes() in a protected call. Errors are caught, logged via w.Log(), and set as the Mach last error, but do not propagate to the caller.
| GCodeRangeString | (string) A range string specifying G-code numbers to register as OEM subs (e.g., "271-272") |
| WrapperModule CreateOrOpenFile | ( | path_to_file | , |
| contents | , | ||
| editor | ) |
Create a file with default contents if it does not exist, then open it in an external editor.
Checks if the file at path_to_file exists via w.FileExists(). If it does not exist, creates it and writes the specified contents. Then locates an editor: if editor is nil, calls w.FindNotepadPP(). If editor is a function, calls it with path_to_file to generate the command. Otherwise uses the editor string directly. Spawns the editor process via winapi.spawn_process() without blocking.
| path_to_file | (string) Full path to the file to create or open |
| contents | (string|nil) Content to write if the file must be created. If nil, creates an empty file |
| editor | (string|function|nil) Path to an editor executable, an editor factory function, or nil to auto-detect Notepad++ |
| WrapperModule CreateOrOpenSubroutine | ( | sub_name | , |
| sub_contents | ) |
Create a stub subroutine file if it does not exist, then open it in an editor.
Constructs the subroutine file path as MACH_DIRECTORY\Subroutines\sub_name.nc. If sub_contents is nil, uses a default placeholder comment. Formats the content using a built-in template that wraps the content with the sub declaration and M99/% terminator. Prefers Notepad++ as the editor; falls back to the G-code editor configured in Mach preferences. Delegates to w.CreateOrOpenFile() for the actual file creation and editor launch.
| sub_name | (string) The subroutine name (e.g., 'O2000'). Used as the filename and the sub declaration label |
| sub_contents | (string|nil) Optional G-code content to include inside the sub body. If nil, uses a default placeholder |
| WrapperModule CreateOutput | ( | dev_name | , |
| io_name | , | ||
| other_info | ) |
Create a dynamic output I/O point via the MachMotion plugin.
Shortcut wrapper around w.CreateIO() that always creates an output (is_input = false). If dev_name is nil, io_name is treated as the I/O name and 'MachMotion' is used as the device.
| dev_name | (string|nil) The device name under which to register the output. If nil, uses 'MachMotion' |
| io_name | (string) The name of the output I/O point to create |
| other_info | (table|nil) Optional configuration table with keys: 'permanent' (boolean), 'type' (string/number), 'description' (string) |
| WrapperModule CreateRegister | ( | dev_name | , |
| reg_name | , | ||
| other_info | ) |
Dynamically create a register via the MachMotion plugin.
Creates a new register by sending a 'CreateRegister' command to the MachMotion plugin via the mm_LuaRequest register. If the register already exists, returns the existing handle immediately without creating a duplicate. If dev_name is nil, reg_name is used as the register name and 'MachMotion' is used as the device. The other_info table controls permanence, type, and description of the created register. Permanent registers are recreated by the plugin on every Mach4 startup.
| dev_name | (string|nil) The device name under which to register the register. If nil, uses 'MachMotion' |
| reg_name | (string) The name of the register to create |
| other_info | (table|nil) Optional configuration table with keys:
|
| WrapperModule CreateSimpleCommand | ( | cmd_name | , |
| action_name | , | ||
| feedback_name | ) |
Create and register a simple pre-canned command with action and feedback options.
Constructs a command table with Action set to "Pre-Canned" and registers it via w.CreateCommand(). If action_name or feedback_name are nil, they default to cmd_name. This is a convenience wrapper that does not persist the command to a file (unlike w.CreateSimpleUserCommand() which also calls w.SaveUserCommand()).
| cmd_name | (string) The name of the command to create |
| action_name | (string|nil) The pre-canned action option name. If nil, defaults to cmd_name |
| feedback_name | (string|nil) The pre-canned feedback source name. If nil, defaults to cmd_name |
| WrapperModule CreateSimpleUserCommand | ( | cmd_name | , |
| action_name | , | ||
| feedback_name | ) |
Create, save, and register a simple user script command with action and feedback options.
Constructs a command table with Action set to "User Script" and registers it both persistently via w.SaveUserCommand() and in the active command registry via w.CreateCommand(). If action_name or feedback_name are nil, they default to cmd_name. Unlike w.CreateSimpleCommand(), this function persists the command to a file in the UserCommands folder so it survives restarts.
| cmd_name | (string) The name of the command to create |
| action_name | (string|nil) The user script action option name. If nil, defaults to cmd_name |
| feedback_name | (string|nil) The user script feedback source name. If nil, defaults to cmd_name |
| WrapperModule CreateSingleMessage | ( | Table | ) |
Create a single-execution GMS monitor message (deprecated - use CreateSystemGlobalMessage).
Maps the legacy single-message table format to the new w.CreateSystemGlobalMessage() format with DeleteAfterExecution set to 1. This means the monitor will delete itself after transitioning back to idle following an armed or active state. Supports mapping of Class, Description, ExtraLines, Time (as ActionDelay), Device/Signal/Active (as conditions), and Action (as Action1/Action2 entries). Redirects to w.CreateSystemGlobalMessage() after conversion.
| Table | (table) Legacy single-message configuration table with keys:
|
| WrapperModule CreateSystemGlobalMessage | ( | Table | ) |
Create a GMS system global monitor message with conditions, actions, and optional extra content.
Serializes the provided configuration table into a pipe-delimited command string and sends it to the GMS plugin via w.SendGMSCommand("CreateMonitor", ...). Supports the full GMS monitor format including: Class, Title, Description, ActionDelay, ActionRepeat, Register, CloseAlert, DeleteAfterExecution, BackgroundColor, HideCloseBtn, SystemOwned, ExtraLines, Action1, Action2, and nested Conditions sets. Also handles backward compatibility with the legacy table format (using ActionClass, Action, TriggerDevice/Signal, PreReqSignals, etc.) by converting it to the new format before serialization.
| Table | (table) GMS monitor configuration table. See inline template comment for full schema. Required key: 'Class' (string) - "Alarm", "Warning", "Notice", or "Process" Optional keys include: Title, Description, ActionDelay, ActionRepeat, Register, CloseAlert, DeleteAfterExecution, BackgroundColor, HideCloseBtn, SystemOwned, ExtraLines, Action1, Action2, Conditions |
| WrapperModule CreateToolInfoFile | ( | ) |
Create a default ToolInfo.lua file and initialize the TOOL_NAMES global table.
Displays an information dialog asking the user to restart Mach before continuing, then writes a default ToolInfo.lua file with two entries (Spindle Empty and Spindle 1-999) to the profile's ToolTables directory via w.WriteTextFile(). Also initializes the TOOL_NAMES global table with the same default entries so they are available without a restart.
| WrapperModule CreateToolSetter | ( | name | ) |
Create a new tool setter entry or return the existing one if the name already exists.
First checks whether a tool setter with the given name already exists via GetToolSetter(). If it does, returns the existing configuration table unchanged. If not, reads the current ToolSetterCount from the MachMotion profile section, increments it, constructs a default configuration table (AutoSetter=false, Height=1, ZPosition=0, etc.), and persists it via WriteToolSetter().
| name | (string) The name of the tool setter to create or retrieve |
References name().
Register a user command action function in user.UserCommands.
Initializes user.UserCommands as an empty table if it does not already exist, then stores the provided function under the given name key. Used to register user-defined action callbacks that can be referenced by command entries with Action set to "User Script".
| name | (string) The name key under which to register the action function |
| func | (function) The user action function to register |
Register a user command feedback function in user.UserCommandsFeedback.
Initializes user.UserCommandsFeedback as an empty table if it does not already exist, then stores the provided function under the given name key. Used to register user-defined feedback callbacks that return a boolean state and can be referenced by command entries with FeedbackSourceType set to "User Script".
| name | (string) The name key under which to register the feedback function |
| func | (function) The user feedback function to register. Should return a boolean state |
| WrapperModule DecrementCommandFeedbackUsage | ( | feedback_name | ) |
Decrement the usage counter for a named command feedback in the Commands device register.
Looks up or creates the feedback register in the Commands device using the feedback register name. Reads the current value, decrements it by 1 (minimum 1 before decrement), and writes the result back. Also decrements the Value counter in m.CurrentActiveFeedbacks for the given feedback_name, clamping it to a minimum of 0.
| feedback_name | (string) The name of the command feedback whose usage counter is to be decremented |
| WrapperModule DecrementCommandUsage | ( | command_name | ) |
Decrement the usage counter for a named command in the Commands device register.
Looks up or creates the command register in the Commands device using the command register name. Reads the current value, decrements it by 1 (minimum 1 before decrement), and writes the result back. Also decrements the Value counter in m.CurrentActiveCommands for the given command_name, clamping it to a minimum of 0.
| command_name | (string) The name of the command whose usage counter is to be decremented |
| WrapperModule DecrementMCodeHoldCount | ( | ) |
Decrement the MCode hold counter by one, with a floor of zero.
Reads the current MCodeHoldCount OEM register value, subtracts one, clamps to zero if the result would be negative, then writes the updated value back.
| WrapperModule DeepCopy | ( | from | , |
| to | ) |
Perform a deep copy of a table, recursively duplicating nested tables.
Attempts to recursively copy all key-value pairs from the source table into a new table. Non-table values (numbers, strings, booleans, etc.) are copied by value. The destination table 'to' is optional; if nil, a new empty table is used.
| from | (table) The source table to copy from |
| to | (table|nil) The destination table to copy into. If nil, a new table is created |
| WrapperModule table deepcopy | ( | orig | , |
| copies | ) |
Create a deep copy of a table, preserving metatables and handling circular references.
Recursively copies all key-value pairs and metatables of a table. A copies table is used internally to detect and correctly handle circular references (shared sub-tables). Non-table values (numbers, strings, booleans, etc.) are returned as-is. Taken from the Lua-users wiki CopyTable page.
| orig | (any) The original value or table to deep-copy |
| copies | (table|nil) Internal table tracking already-copied objects. Must not be passed by callers |
| WrapperModule DeleteAllUserCommands | ( | ) |
Delete all user command INI files from the UserCommands folder.
Retrieves all filenames in the user command folder via w.GetUserCommandFolder() and removes each file using os.remove(). This permanently deletes all persisted user command definitions. In-memory command registrations in m.Commands are not affected.
| WrapperModule DeleteMachMotionLogFile | ( | ) |
Delete the MachMotion.log file from the Mach4 directory.
Calls os.remove() to delete the file at MACH_DIRECTORY/MachMotion.log. No error is raised if the file does not exist.
| WrapperModule DirectoryExists | ( | Path | ) |
Check to see if a directory exists.
WrapperModule.DirectoryExists
Check to see if a directory exists.
| WrapperModule DisableGMSMessage | ( | Handle | , |
| disable | ) |
Temporarily disable or re-enable a GMS monitor message.
Sends a "MonitorDisable" command to GMS with the handle and a disable flag (1 to disable, 0 to enable). Unlike FullyDisableGMSMessage(), a message disabled by this function will automatically re-enable itself when all of its conditions return to the idle state. If disable is nil, it defaults to true.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| disable | (boolean|nil) If true or nil, disables the message. If false, re-enables it |
| WrapperModule DisableProbeOutput | ( | inst | ) |
Deactivate the probe enable output signal if it is configured.
Checks whether the "ProbeEnableOutput" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If it is mapped, sets the signal to false via w.SetOEMParamSig(). Raises an error via w.Error() if the signal set operation fails. Does nothing if the signal is not mapped.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DistanceFunction | ( | A1 | , |
| A2 | , | ||
| B1 | , | ||
| B2 | , | ||
| C1 | , | ||
| C2 | ) |
Calculate the Euclidean distance between two points in up to three dimensions.
Accepts up to three pairs of coordinates (A1/A2, B1/B2, C1/C2). Any pair where either value is nil or non-numeric is excluded from the calculation. Returns the 1D absolute difference, 2D Euclidean distance, or 3D Euclidean distance depending on how many valid coordinate pairs are provided. Returns an error if no valid pairs are given or if the radicand is negative.
| A1 | (number|nil) First coordinate of the first dimension start point |
| A2 | (number|nil) First coordinate of the first dimension end point |
| B1 | (number|nil) Second dimension start point |
| B2 | (number|nil) Second dimension end point |
| C1 | (number|nil) Third dimension start point (optional) |
| C2 | (number|nil) Third dimension end point (optional) |
| WrapperModule Distribute | ( | data | ) |
Distribute a number of objects evenly across a one-dimensional space.
Computes integer start, end, and length values for each object so that they fit within the given space subject to optional padding and size constraints. Uses the minimum padding to calculate the largest possible item size, then adjusts padding to distribute remaining space. Padding and item size are floored to integers.
| data | (table) Input configuration table with keys:
|
| WrapperModule DoesExistGoToPosition_MachineZero | ( | inst | ) |
Check whether a Machine Zero GoTo position has been configured.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions checking for one with MachineZeroPosition == true. Returns true as soon as a machine zero position is found, false if none exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesExistGoToPosition_Park | ( | inst | ) |
Check whether a Park GoTo position has been configured.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions checking for one with ParkPosition == true. Returns true as soon as a park position is found, false if none exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesExistGoToPosition_PartZero | ( | inst | ) |
Check whether a Part Zero GoTo position has been configured.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions checking for one with PartZeroPosition == true. Returns true as soon as a part zero position is found, false if none exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesExistGoToPosition_ToolChange | ( | inst | ) |
Check whether a Tool Change GoTo position has been configured.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions checking for one with ToolChangePosition == true. Returns true as soon as a tool change position is found, false if none exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesExistGoToPosition_ToolSetter | ( | inst | ) |
Check whether a Tool Setter GoTo position has been configured.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions checking for one with ToolSetterPosition == true. Returns true as soon as a tool setter position is found, false if none exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesOEMParamExist | ( | RegName | , |
| inst | ) |
Check whether an OEM parameter register exists for the specified instance.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), then attempts to get the register handle via w.GetRegHandle(). Returns true if the handle is non-zero, indicating the register exists, or false if the handle is zero.
| RegName | (string) The name of the OEM parameter register to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DoesParameterExist | ( | param | , |
| inst | ) |
Check whether a Mach4 control parameter exists, with caching.
-------------------— Mach Paramter Wrappers ----------------------—
Checks the cache first using a cache name derived from the instance number. If the result is cached, returns the cached value. Otherwise calls mc.mcCntlGetParameterExists() and caches the result. The cache name includes the instance number when inst is provided.
| param | (number) The Mach4 control parameter number to check |
| inst | (number|nil) The Mach4 instance handle. If nil, uses current instance for the API call but omits instance from cache key |
| WrapperModule eGetOEMParamSig | ( | SigName | , |
| inst | ) |
Get the state of a signal or I/O point referenced by an OEM parameter register and raise an error on failure.
Calls w.GetOEMParamSig() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMParamSig().
| SigName | (string) The OEM parameter register name of the signal to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMParamValue | ( | RegName | , |
| inst | ) |
Get an OEM parameter numeric value and raise an error on failure.
Calls w.GetOEMParamValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMParamValue().
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMParamValueCached | ( | RegName | , |
| inst | ) |
Get a cached OEM parameter numeric value and raise an error on failure.
Calls w.GetOEMParamValueCached() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMParamValueCached().
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMParamValueString | ( | RegName | , |
| inst | ) |
Get an OEM parameter string value and raise an error on failure.
Calls w.GetOEMParamValueString() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMParamValueString().
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMParamValueStringCached | ( | RegName | , |
| inst | ) |
Get a cached OEM parameter string value and raise an error on failure.
Calls w.GetOEMParamValueStringCached() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMParamValueStringCached().
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMRegValue | ( | RegName | , |
| inst | ) |
Get an OEM register numeric value and raise an error on failure.
Calls w.GetOEMRegValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMRegValue().
| RegName | (string) The name of the OEM register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetOEMRegValueString | ( | RegName | , |
| inst | ) |
Get an OEM register string value and raise an error on failure.
Calls w.GetOEMRegValueString() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetOEMRegValueString().
| RegName | (string) The name of the OEM register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetParamSig | ( | Device | , |
| SigName | , | ||
| inst | ) |
Get the state of a signal or I/O point referenced by a parameter register and raise an error on failure.
Calls w.GetParamSig() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetParamSig().
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name of the parameter signal to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetRegValue | ( | Device | , |
| RegName | , | ||
| inst | ) |
Get the numeric value of a register and raise an error on failure.
Calls w.GetRegValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetRegValue().
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eGetSignalState | ( | name | , |
| inst | ) |
Get the state of a signal by signal ID and raise an error on failure.
Calls w.GetSignalState() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.GetSignalState().
| name | (number) The signal ID to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule eIsSignalMapped | ( | Signal | , |
| inst | ) |
Check whether a signal is mapped to an I/O point and raise an error on failure.
Calls w.IsSignalMapped() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.IsSignalMapped().
| Signal | (number) The signal ID to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eIsSignalMappedAndEnabled | ( | Signal | , |
| inst | ) |
Check whether a signal is mapped and enabled, and raise an error on failure.
Calls w.IsSignalMappedAndEnabled() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.IsSignalMappedAndEnabled().
| Signal | (number) The signal ID to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ElapsedTime | ( | from_ll | , |
| to_ll | ) |
Calculate elapsed time in milliseconds between two wxLongLong timestamps.
Computes the difference between two wxGetLocalTimeMillis() timestamps while avoiding Lua precision loss warnings from wxLua/mcLua when subtracting 64-bit values directly. Handles 32-bit overflow of the low word. If from_ll is 0, returns the lower 32 bits of to_ll. If to_ll is not specified, uses the current time.
| from_ll | (userdata) The starting wxLongLong timestamp (from wx.wxGetLocalTimeMillis()) |
| to_ll | (userdata|nil) The ending wxLongLong timestamp. If nil, uses the current time |
| WrapperModule EnableProbeOutput | ( | delay | , |
| inst | ) |
Activate the probe enable output signal and optionally wait for the probe error input to clear.
Checks whether the "ProbeEnableOutput" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If it is mapped, sets the signal to true via w.SetOEMParamSig() and raises an error via w.Error() if the set operation fails. If a delay is specified and greater than zero, displays a please-wait dialog for that duration before proceeding. If the "ProbeErrorInput" OEM parameter signal is also mapped, waits for it to go false (inactive) with a 1000ms timeout via w.PleaseWaitDialog(). Does nothing if neither signal is mapped.
| delay | (number|nil) Optional delay in milliseconds to wait before checking the error input. If nil or 0, no delay dialog is shown |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule EnumerateProfileSection | ( | section | , |
| inst | ) |
Enumerate all key-value pairs in a Mach4 profile section.
Iterates over all entries in the specified profile section using mc.mcProfileEnumerateSection(), collecting each key and its string value via mc.mcProfileGetString(). Returns a table mapping key names to their string values. Stops iteration when the return code is not MERROR_NOERROR or the next index is negative.
| section | (string) The profile section name to enumerate |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eRegSendCommand | ( | Device | , |
| RegName | , | ||
| cmd | , | ||
| inst | ) |
Send a register command and raise an error on failure.
Calls w.RegSendCommand() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.RegSendCommand().
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the command register to send the command to |
| cmd | (string) The command string to send to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule Error | ( | msg | , |
| data | ) |
Raise a Lua error with a rich error object containing stack trace and machine context.
Creates a structured error table containing the message, Lua traceback, debug stack frames with parameters, Mach4 machine state (state name, G-code file, G-code line), and version information. If the input is already an error object table (with a Message field), re-raises it directly. Defines methods on the error object: GetMachInfo(), GetMessage(), GetVersionInfo(), GetTraceback(), and GetAlarmMessage(). Logs the traceback and error details before raising.
| msg | (string|number|table) The error message, a negative mc error code, or an existing error object |
| data | (any|nil) Optional additional data to attach to the error object as AdditionalData |
| WrapperModule ErrorHandler | ( | err | ) |
xpcall error handler that normalizes any error value into a rich error object
If the caught error value is not already a table, passes it through w.pcall(w.Error, err) to convert it into a structured error object with stack trace and machine context. If it is already a table, returns it as-is. Intended for use as the message handler argument to xpcall().
| err | (any) The error value caught by xpcall |
| WrapperModule ErrorMessage | ( | msg_or_obj | , |
| appendmessage | ) |
Format an error object or string into a human-readable error message string.
If msg_or_obj is a table with a Message field, extracts the message and appends any traceback information from GetTraceback() or Traceback fields. If it is not a table with a Message field, converts it directly to a string via tostring(). An optional appendmessage string is appended to the result, prefixed with "; ". This function is intended for use after a pcall when you need to present or log an error without re-raising it.
| msg_or_obj | (string|table) The error value to format - either a plain string or an error object created by w.Error() |
| appendmessage | (string|nil) Optional additional context to append to the error message. If nil, nothing is appended |
| WrapperModule EscapeCSV | ( | s | ) |
Escape a string value for safe inclusion in a CSV field.
If the string contains a comma or a double-quote character, wraps the entire string in double quotes and escapes any internal double-quote characters by doubling them (""). If the string contains neither character, it is returned unchanged.
| s | (string) The string value to escape for CSV output |
| WrapperModule eSetOEMParamSig | ( | RegName | , |
| val | , | ||
| inst | ) |
Set an OEM parameter signal and raise an error if the operation fails.
Calls w.SetOEMParamSig() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetOEMParamSig().
| RegName | (string) The OEM parameter register name of the signal to set |
| val | (boolean) The desired signal state to set |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetOEMParamValue | ( | RegName | , |
| val | , | ||
| inst | ) |
Set an OEM parameter value and raise an error on failure.
Calls w.SetOEMParamValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetOEMParamValue().
| RegName | (string) The name of the OEM parameter register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetOEMParamValueString | ( | RegName | , |
| val | , | ||
| inst | ) |
Set an OEM parameter string value and raise an error on failure.
Calls w.SetOEMParamValueString() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetOEMParamValueString().
| RegName | (string) The name of the OEM parameter register to set |
| val | (string) The string value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetOEMRegValue | ( | RegName | , |
| val | , | ||
| inst | ) |
Set an OEM register value and raise an error on failure.
Calls w.SetOEMRegValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetOEMRegValue().
| RegName | (string) The name of the OEM register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetParamSig | ( | Device | , |
| SigName | , | ||
| Val | , | ||
| inst | ) |
Set a parameter signal and raise an error if the operation fails.
Calls w.SetParamSig() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetParamSig().
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name of the parameter signal to set |
| Val | (boolean) The desired signal state to set |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetRegValue | ( | Device | , |
| RegName | , | ||
| val | , | ||
| inst | ) |
Set the numeric value of a register and raise an error on failure.
Calls w.SetRegValue() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetRegValue().
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule eSetSignalState | ( | name | , |
| val | , | ||
| inst | ) |
Set the state of a signal and raise an error on failure.
Calls w.SetSignalState() with the provided arguments and raises a Lua error via w.Error() if the success flag is false. This is the error-raising variant of w.SetSignalState().
| name | (number) The signal ID whose state is to be set |
| val | (number|boolean) The desired signal state |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule EvaluateLuaExpression | ( | expr_string | ) |
Evaluate a simple Lua expression that returns a value or series of values.
WrapperModule.EvaluateLuaExpression
This function evaluates a simple Lua expression (like a table definition or a mathematical expression) and returns the result. It is not intended for running code snippets, though it will be able to run nearly any one-liner.
Examples – evaluate a string-ified table local my_table = (w.EvaluateLuaExpression('{["keyA"]=1;["keyB"]=2}')).data – evaluate a simple arithmetic expression local area (w.EvaluateLuaExpression("2 * 2 * 3.1415926")).data – This is the (crazy) way to evaluate multiple statements as a "one-liner." w.EvaluateLuaExpression("(w.wxMessageBox('L1'),w.wxMessageBox('L2'))")
| WrapperModule eWaitForOEMParamSig | ( | Signal | , |
| State | , | ||
| Timeout | , | ||
| AlarmMessage | , | ||
| inst | ) |
Wait for an OEM parameter signal to reach a specified state, raising errors instead of returning failure.
Similar to WaitForOEMParamSig() but uses w.Error() instead of returning false on failure. Validates all inputs and raises errors for invalid types or ranges. Constructs a GMS alarm dialog table with signal info for display during the wait. In screen chunk context, delegates to w.WaitOnCondition() with WaitType.OEMParamSig. In M-code chunk context, polls the OEM parameter signal directly in a repeat loop with 2ms sleep intervals. Machine disable during the wait raises an error with the disabled_msg.
| Signal | (string) The OEM parameter signal name to monitor |
| State | (boolean) The desired signal state to wait for (true or false) |
| Timeout | (number) Maximum wait time in milliseconds. Must be >= 0 |
| AlarmMessage | (string|nil) Custom alarm message. If nil, generates a default message from the signal description |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References AlarmMessage().
| WrapperModule FunctionQueue Execute | ( | ) |
Execute all registered functions in this FunctionQueue group.
Iterates through all registered functions and calls each one via w.pcall(). If any function raises an error, the error is logged but execution continues for remaining functions. After all functions have been called, if any errors occurred, sets the Mach last error message with a reference to check the log for details.
| WrapperModule execute | ( | command | , |
| window_style | , | ||
| wait_on_return | ) |
| f | ( | x | ) |
Return a function that calculates y-values for a parabola passing through three given points.
Computes the coefficients A, B, and C for the parabola f(x) = Ax^2 + Bx + C that passes through the three specified (x, y) coordinate pairs using the standard algebraic formula. Returns a closure function that accepts an x value and returns the corresponding y value. The vertex of the resulting parabola is at (-B/2A, C - B^2/4A).
| x0 | (number) The x-coordinate of the first point |
| y0 | (number) The y-coordinate of the first point |
| x1 | (number) The x-coordinate of the second point |
| y1 | (number) The y-coordinate of the second point |
| x2 | (number) The x-coordinate of the third point |
| y2 | (number) The y-coordinate of the third point |
| WrapperModule FileExists | ( | FileName | ) |
Check whether a file exists and is accessible for reading.
-------------------— Check If File/Dir Exists -------------------—
Attempts to open the file in read mode using io.open(). Returns false if the file cannot be opened (does not exist or is not accessible). Returns an error if FileName is not a string.
| FileName | (string) Full path to the file to check |
| WrapperModule FileRename | ( | old_name | , |
| new_name | ) |
Rename or move a file from one path to another.
Wraps os.rename() with standard triple-return error handling. Returns nil and a formatted error message if the rename operation fails.
| old_name | (string) The current full path of the file |
| new_name | (string) The new full path to rename or move the file to |
| WrapperModule FileSizeBytes | ( | filepath | ) |
Get the size of a file in bytes using the Lua File System library.
-------------------— Get File Size -------------------—
Uses lfs.attributes() to retrieve the file size. Raises an error if the lfs module is not available.
| filepath | (string) Full path to the file to measure |
| WrapperModule FileSizeKilobytes | ( | filepath | ) |
Get the size of a file in kilobytes.
Delegates to WrapperModule.FileSizeBytes() and divides the result by 1024.
| filepath | (string) Full path to the file to measure |
| WrapperModule FileSizeMegabytes | ( | filepath | ) |
Get the size of a file in megabytes.
Delegates to WrapperModule.FileSizeKilobytes() and divides the result by 1024.
| filepath | (string) Full path to the file to measure |
| WrapperModule FilterProbePositions | ( | ) |
Placeholder function that always raises an error when called.
This function exists as a stub and immediately raises a Lua error via w.Error() indicating that WrapperModule.FilterProbePositions() should not be used. It is retained for backward compatibility but has no functional implementation.
| WrapperModule FindClosestPath | ( | CurrentX | , |
| CurrentY | ) |
Find the G-code line whose path segment is closest to the current or specified XY position.
Iterates over all G-code lines in the currently loaded file (via _FindClosestPath()), computing the closest point on each motion segment to the given position using w.FindPath(). Displays a wxProgressDialog while scanning if running in a screen chunk. Uses w.pcall() for error protection and logs elapsed time on completion.
| CurrentX | (number|nil) X coordinate to measure from. If nil, reads current machine position |
| CurrentY | (number|nil) Y coordinate to measure from. If nil, reads current machine position |
| WrapperModule FindFile | ( | filename | , |
| directory | , | ||
| ext_table | , | ||
| inst | ) |
Recursively search a directory tree for a file matching the given name and extension.
Walks the directory tree starting at directory, recursing into subdirectories. For each file found, checks whether its base name matches filename (with a dot appended) and whether its extension is in ext_table. If the matching file exists on disk (verified via wx.wxFileExists()), returns its full path. If directory is nil or empty, defaults to MACH_DIRECTORY\GCodeFiles. If ext_table is nil, defaults to {".tap", ".nc", ".cnc", ".anc", ".out", ".txt"}.
| filename | (string) The base file name to search for (without extension) |
| directory | (string|nil) The root directory to search. Defaults to MACH_DIRECTORY\GCodeFiles if nil or empty |
| ext_table | (table|nil) Array of valid file extensions (e.g., {".nc", ".tap"}). Defaults to a standard set if nil |
| inst | (number|nil) The Mach4 instance handle. If nil, uses current instance |
| WrapperModule FindNotepadPP | ( | skip_registry | ) |
Attempt to locate the installation path of Notepad++, caching the result.
First checks a cached path in WrapperModule.__path_to_npp. If not cached, searches the Windows registry under 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\notepad++.exe' (unless skip_registry is true). If not found in the registry, searches standard Program Files directories. Caches the found path for subsequent calls.
| skip_registry | (boolean|nil) If true, skips the registry search and only checks standard directories |
| WrapperModule FindPath | ( | LineNum | , |
| XPos | , | ||
| YPos | ) |
Find the closest point on a G-code path segment to a given XY position.
Wraps _FindPath() in a protected call via w.pcall(). Locates the nearest point on the motion segment at LineNum by scanning surrounding lines to determine the start and end positions, then calculates the closest point for linear (G00/G01) and arc (G02/G03) moves. Returns the closest point coordinates and distance in a table.
| LineNum | (number) The G-code line number to evaluate (0-based index) |
| XPos | (number|nil) Current X position. If nil, reads from machine position |
| YPos | (number|nil) Current Y position. If nil, reads from machine position |
| WrapperModule FlushProfile | ( | ) |
Flush the Mach4 profile to disk.
Calls mc.mcProfileFlush() to write all pending profile changes to the INI file on disk. If the flush fails, logs an error message with the error code and description. Always logs a message indicating the flush attempt.
| WrapperModule FromCSVToTable | ( | s | ) |
Convert a single CSV line string into a Lua table of field values.
Parses a single line of CSV data, handling quoted fields that may contain commas. Double-quoted strings within quoted fields are unescaped to single quotes. An implicit trailing comma is appended to simplify parsing. Raises a Lua error if an unmatched quote is found.
| s | (string) The CSV line string to parse (a single row of CSV data) |
| WrapperModule FromMultiLineCSVToTable | ( | s | ) |
Convert a multi-line CSV string into a two-dimensional Lua table.
Splits the input string by newlines and parses each line using w.FromCSVToTable(). Each parsed line becomes a row (array) in the returned outer table. Empty lines at the end of the string may produce an empty trailing row.
| s | (string) The multi-line CSV string to parse |
| WrapperModule FullyDisableGMSMessage | ( | Handle | , |
| disable | ) |
Permanently disable or re-enable a GMS monitor message.
Sends a "MonitorDisable" command to GMS with the handle and a permanent disable flag (3 to permanently disable, 2 to permanently re-enable). Unlike DisableGMSMessage(), a message disabled by this function will NOT automatically re-enable when conditions go idle - it remains in its disabled or enabled state until explicitly changed by another call to this function. If disable is nil, it defaults to true.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| disable | (boolean|nil) If true or nil, permanently disables the message. If false, permanently re-enables it |
| func_name | ( | ) |
Checkpoint-instrumented wrapper function template for long-running operations.
This is a usage template showing how to use DbgCheckPoint to instrument a function. The actual function being documented here is the inner function (e.g., _func_name) that performs the work and calls _fn_check:CHECK() at key points. The outer function calls w.Protected(_func_name) to catch and report any errors along with checkpoint context.
Referenced by GetInstance().
| WrapperModule FunctionButtonMDI | ( | Command | , |
| inst | ) |
Execute an MDI command after verifying machine state and prompting for cycle start confirmation.
Checks that the machine is enabled (using MACH_ENABLED_INST) and idle (using MACH_STATE_INST). If not enabled, displays a warning and returns an error. If not idle, displays a warning and returns success (no-op). Otherwise, shows a cycle start confirmation dialog via m.CycleStartDialog(). If confirmed, executes the command via w.MDICommandNoDialog().
| Command | (string) The MDI command string to execute after confirmation |
| inst | (number|nil) The Mach4 instance handle. If nil, uses the selected instance |
| WrapperModule FunctionCompleted | ( | CustomMessage | , |
| FunctionName | , | ||
| LineNumber | , | ||
| FileName | ) |
Log function completion with context information and return a formatted status message.
Records a completion message to the Mach4 log via mc.mcCntlLog(), including the calling function name, optional custom message, caller chain information, source file, and line number. Automatically extracts caller context from the debug stack. If CustomMessage is a string, it is prepended with a space; otherwise defaults to " completed successfully". The instance number is appended to the log message for multi-instance diagnostics.
| CustomMessage | (string|nil) Optional custom completion message. If nil, uses " completed successfully" |
| FunctionName | (string|nil) Override function name for the log message. If nil, extracted from debug stack |
| LineNumber | (number|nil) Override line number for the log message. If nil, extracted from debug stack |
| FileName | (string|nil) Override source file name for the log message. If nil, extracted from debug stack |
| WrapperModule FunctionError | ( | CustomMessage | , |
| FunctionName | , | ||
| LineNumber | , | ||
| FileName | ) |
Log a function error with context information and return a formatted error message string.
Records an error message to the Mach4 log via mc.mcCntlLog(), including the calling function name, caller chain, source file, and line number. Automatically extracts caller context from the debug stack using w.debug.GetNextUsefulStackFrame(). If in debugging mode, also sets the last error string via mc.mcCntlSetLastError(). Does NOT raise an exception - returns the CustomMessage string for use as a return value in the standard triple-return pattern.
| CustomMessage | (string) The error message text to log and return |
| FunctionName | (string|nil) Override function name for the log. If nil, extracted from debug stack |
| LineNumber | (number|nil) Override line number for the log. If nil, extracted from debug stack |
| FileName | (string|nil) Override source file name for the log. If nil, extracted from debug stack |
| WrapperModule GCEditEditor | ( | path_to_gceditexe | ) |
Create a batch code generator function for opening a file in GCEdit.
Returns a closure that, when called with a file path, generates a batch command string to open that file in the specified GCEdit executable using START. The generated command ignores exit code 2 (which GCEdit sometimes returns even on success) and exits with the error level for any exit code >= 3.
| path_to_gceditexe | (string) Full path to the GCEdit executable |
| WrapperModule GCodeCNTL1MSTToggle | ( | inst | ) |
Toggle the G-code CNTL1 MST (suppress M/S/T waits) bit on or off.
Reads the current state of the CNTL1 MST bit via GetGCodeCNTL1MST(). If it is currently set, clears it via ResetGCodeCNTL1MST(); if it is currently clear, sets it via SetGCodeCNTL1MST().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GcodeInterpGetPos | ( | InterpTool | ) |
Get the G-code interpreter's interpolated XY position adjusted for X/Y tool offsets.
Wraps mc.mcCntlGcodeInterpGetPos() to account for X and Y tool offsets that the standard API does not include. Reads the current tool and the interpreter tool (InterpTool), retrieves their respective X and Y mill tool offsets via mc.mcToolGetData(), and adjusts the interpreter X/Y positions by the difference between the two tools' offsets. Returns a table with 'X' and 'Y' fields.
| InterpTool | (number) The tool number for which to calculate the interpolated position |
| WrapperModule geom GenericParabola | ( | x0 | , |
| y0 | , | ||
| x1 | , | ||
| y1 | , | ||
| x2 | , | ||
| y2 | ) |
Return a function that calculates y-values for a parabola passing through three given points.
Computes the coefficients A, B, and C for the parabola f(x) = Ax^2 + Bx + C that passes through the three specified (x, y) coordinate pairs using the standard algebraic formula. Returns a closure function that accepts an x value and returns the corresponding y value. The vertex of the resulting parabola is at (-B/2A, C - B^2/4A).
| x0 | (number) The x-coordinate of the first point |
| y0 | (number) The y-coordinate of the first point |
| x1 | (number) The x-coordinate of the second point |
| y1 | (number) The y-coordinate of the second point |
| x2 | (number) The x-coordinate of the third point |
| y2 | (number) The y-coordinate of the third point |
| WrapperModule GenericTextEntry | ( | message | , |
| title | ) |
Display a modal text entry dialog and return the value entered by the user.
Creates a standard dialog with a label, a single-line text input field, and OK/Cancel buttons. Blocks until the user clicks OK or Cancel. Returns the entered string on OK, or an empty string if Cancel is pressed or the dialog is dismissed without input.
| message | (string|nil) The prompt label to display above the text field. Defaults to "Enter value:" if nil |
| title | (string|nil) The dialog window title. Defaults to "" if nil |
| WrapperModule GetActiveCommands | ( | ) |
Retrieve all currently active commands and their usage counts.
Loads all registered commands via w.GetAllCommands(), then checks the Commands device register for each command's usage counter. Returns only those commands whose counter is greater than zero, along with their current count value and full command data table. Logs each command count when debugging is active.
| WrapperModule GetActiveFeedbacks | ( | ) |
Retrieve all currently active command feedbacks and their usage counts.
Loads all registered feedbacks via w.GetAllFeedbacks(), then checks the Commands device register for each feedback's usage counter. Returns only those feedbacks whose counter is greater than zero, along with their current count value. Logs each feedback count when debugging is active.
| err GetAlarmMessage | ( | ) |
Build a GMS alarm message table from the error object for display or delivery.
If the error object's AdditionalData is a table with an ActionClass or Class field, appends MachInfo and Stack Trace extra lines to that table and sets Description if missing. Otherwise constructs a standard GMS alarm table with Class="Alarm", Title="Alarm Active", Description set to the error message, and two ExtraLines panels for Mach Info and Stack Trace. Action1 opens the GMS notification panel.
| WrapperModule GetAlarmMessage | ( | e | , |
| extra | ) |
Format an error object or string into a GMS alarm message string.
If the error object has a GetAlarmMessage() method, delegates to that method to produce the formatted message. Otherwise, converts the object to a string via tostring() and optionally appends the extra parameter. This function is intended to produce a safe, human-readable alarm message from any type of error value - whether a structured error object from w.Error() or a plain string.
| e | (string|table) The error value to format - either a plain string or an error object created by w.Error() |
| extra | (string|nil) Optional additional text to append when the input is not a structured error object. If nil, nothing is appended |
| WrapperModule GetAllActions | ( | ) |
Retrieve all registered command action functions from m.CommandActions and user.UserCommands.
Initializes m.CommandActions as an empty table if it does not already exist. Merges all functions from user.UserCommands (if defined) into the actions table so that user-defined actions are included alongside pre-canned ones.
| WrapperModule GetAllAutoToolSetters | ( | ) |
Retrieve all configured automatic tool setters.
Calls w.GetAllToolSetters() to load all configured tool setters, then removes any entry whose AutoSetter field is not true, decrementing the count accordingly. Returns the filtered table containing only auto tool setters and the updated count.
| WrapperModule GetAllCommands | ( | ) |
Retrieve all registered commands from m.Commands and all user command INI files.
Initializes m.Commands as an empty table if it does not already exist. Loads all user commands from disk via w.GetAllUserCommands() and merges them into m.Commands keyed by Name. Returns the combined table of all pre-canned and user-defined commands.
| WrapperModule GetAllDevices | ( | filter | ) |
Retrieve all registered devices of a specified type.
Iterates over all devices using mc.mcDeviceGetNextHandle() with the given filter type, collecting each device name and handle into a table. If filter is nil or not a number, defaults to mc.DEV_TYPE_ALL to return devices of every type.
| filter | (number|nil) Device type filter constant (e.g., mc.DEV_TYPE_IO, mc.DEV_TYPE_REG). If nil, returns all device types |
References filter().
| WrapperModule GetAllFeedbacks | ( | ) |
Retrieve all registered command feedback functions from m.CommandFeedbacks and user.UserCommandsFeedback.
Initializes m.CommandFeedbacks as an empty table if it does not already exist. Merges all functions from user.UserCommandsFeedback (if defined) into the feedbacks table so that user-defined feedback callbacks are included alongside pre-canned ones.
| WrapperModule GetAllInputSignals | ( | ) |
Retrieve all input signals registered in the current Mach4 instance.
Shortcut wrapper around w.GetAllSignals() that always retrieves input signals (input = true).
| WrapperModule GetAllIOForDevice | ( | device_handle | ) |
Retrieve all I/O points registered under a specific device handle.
Iterates over all I/O points for the given device handle using mc.mcIoGetNextHandle(), collecting each I/O name and handle into a table. Returns an empty table if device_handle is not a valid number.
| device_handle | (number) The device handle whose I/O points are to be enumerated |
| WrapperModule GetAllIOPaths | ( | ) |
Retrieve full device/IO path strings for all I/O points across all devices.
Gets all I/O devices via w.GetAllDevices(mc.DEV_TYPE_IO), then iterates each device to collect all its I/O points via w.GetAllIOForDevice(). Combines device and I/O names into "device/io_name" path strings and returns them as an array.
| WrapperModule GetAllManualToolSetters | ( | ) |
Retrieve all configured manual (non-auto) tool setters.
Calls w.GetAllToolSetters() to load all configured tool setters, then removes any entry whose AutoSetter field is true, decrementing the count accordingly. Returns the filtered table containing only manual tool setters and the updated count.
| WrapperModule GetAllOutputSignals | ( | ) |
Retrieve all output signals registered in the current Mach4 instance.
Shortcut wrapper around w.GetAllSignals() that always retrieves output signals (input = false).
| WrapperModule GetAllSignals | ( | input | ) |
Retrieve all input or output signals registered in the current Mach4 instance.
Iterates over either the input signal range (mc.MC_ISIGS_START to mc.MC_ISIGS_FINISH) or the output signal range (mc.MC_OSIGS_START to mc.MC_OSIGS_FINISH) depending on the input parameter. For each signal handle found, retrieves the signal description via mc.mcSignalGetInfo() and appends any user-defined description from the profile. Returns a table mapping description strings to signal ID numbers.
| input | (boolean) If true, retrieves input signals; if false, retrieves output signals |
| WrapperModule GetAllToolSetters | ( | ) |
Read all configured tool setters from the Mach4 profile and return them as a keyed table.
Reads the ToolSetterCount from the MachMotion profile section and iterates through each tool setter entry. Handles both integer-keyed ("ToolSetter1") and float-keyed ("ToolSetter1.0") section names for Lua 5.3 compatibility. For each found entry, reads all configuration fields (AutoSetter, FixturesOffsets, FixtureOffsetMode, ProbeInput, ProbeName, ProbeInputSignal, DisableSoftlimits, Height, ZPosition, GoToPosition, EndGoToPosition) and stores them in a table keyed by the setter's name string. Migrates float-keyed sections to integer-keyed sections via WriteToolSetter() if needed.
| WrapperModule GetAllUserCommands | ( | ) |
Read and return all user command configuration tables from the UserCommands folder.
Retrieves all INI filenames from the user command folder via w.GetUserCommandFolder(), then reads and parses each file using w.ReadUserCommandFile(). Collects all command entries (ensuring each has a Name field) into a flat array and returns it.
| WrapperModule GetAnalogInput | ( | idx | , |
| inst | ) |
Get the current value of an analog input channel.
Reads the analog input at the specified index via mc.mcAnalogInputRead(). Returns an error if the index parameter is not a number.
| idx | (number) The analog input channel index to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAnalogOutput | ( | idx | , |
| inst | ) |
Get the current value of an analog output channel.
Reads the analog output at the specified index via mc.mcAnalogOutputRead(). Returns an error if the index parameter is not a number.
| idx | (number) The analog output channel index to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAppDataRoaming | ( | ) |
Get the Windows roaming AppData directory path with fallback methods.
Attempts to retrieve the roaming AppData directory using two methods in order: Method1 (Windows Shell API via wxStandardPaths) and Method2 (APPDATA environment variable). If both methods fail, returns a hardcoded fallback path. Warnings are logged for each failed attempt.
| WrapperModule GetAppDataRoaming_Method1 | ( | ) |
Get the Windows roaming AppData directory path using the Windows Shell API.
Retrieves the roaming AppData directory by calling wx.wxStandardPaths.MSWGetShellDir() with the CSIDL_APPDATA constant (26). This is the preferred method as it uses the Windows Shell API directly rather than relying on environment variables.
| WrapperModule GetAppDataRoaming_Method2 | ( | ) |
Get the Windows roaming AppData directory path using the APPDATA environment variable.
Retrieves the roaming AppData directory by reading the APPDATA environment variable via os.getenv(). This is a fallback method used when Method1 (Windows Shell API) is unavailable. Correct for Windows 10; behavior on Windows 7 may vary.
| WrapperModule GetAxisChildMotorID | ( | AxisID | , |
| inst | ) |
Get an array of all motor IDs mapped to a specified axis.
Validates that AxisID is a number within the valid axis range, then iterates through all motor slots (0 to MC_MAX_AXIS_MOTORS-1) via mc.mcAxisGetMotorId() to collect all valid motor IDs mapped to the axis. Returns the array of motor IDs and a success flag, or nil and false if no motors are mapped or the AxisID is invalid.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to query |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisIsMoving | ( | axis | , |
| inst | ) |
Check whether the specified axis is currently moving in either direction.
Reads the axis velocity via mc.mcAxisGetVel() and returns true if the absolute value of the velocity meets or exceeds the _axis_moving_threshold. Returns false if the axis ID is out of range.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisIsMovingNegative | ( | axis | , |
| inst | ) |
Check whether the specified axis is currently moving in the negative direction.
Reads the axis velocity via mc.mcAxisGetVel() and returns true if the velocity is less than the negative _axis_moving_threshold. Returns false if the axis ID is out of range.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisIsMovingPositive | ( | axis | , |
| inst | ) |
Check whether the specified axis is currently moving in the positive direction.
Reads the axis velocity via mc.mcAxisGetVel() and returns true if the velocity exceeds the positive _axis_moving_threshold. Returns false if the axis ID is out of range.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisIsNotMoving | ( | axis | , |
| inst | ) |
Check whether the specified axis is stationary (not moving in either direction).
Reads the axis velocity via mc.mcAxisGetVel() and returns true only if the velocity is within the _axis_moving_threshold in both the positive and negative directions. Returns false if the axis ID is out of range.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisLetter | ( | axis | ) |
Get the single-letter G-code identifier for a Mach4 axis ID.
Maps standard axis ID constants (mc.X_AXIS through mc.C_AXIS) to their single-letter G-code identifiers ("X" through "C"). Returns an empty string for any axis ID that does not correspond to one of the six standard coordinated axes.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.C_AXIS) |
| WrapperModule GetAxisMachinePos | ( | AxisID | , |
| position | ) |
Get the machine-coordinate position of an axis.
If position is nil, reads the machine position directly via mc.mcAxisGetMachinePos(). If position is provided, returns it unchanged. This function provides a consistent interface for obtaining machine coordinates whether the position is known or needs to be read.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| position | (number|nil) An optional position value. If provided, returned as-is; if nil, read from Mach4 |
| WrapperModule GetAxisName | ( | axis | ) |
Get the human-readable name string for a Mach4 axis ID.
Maps standard axis ID constants (mc.X_AXIS through mc.C_AXIS) to their single-letter names ("X" through "C"). For out-of-band axes (axis IDs beyond C_AXIS), returns a formatted string "OB(n)" indicating an out-of-band axis number.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.A_AXIS) |
| WrapperModule GetAxisPos | ( | AxisID | , |
| position | ) |
Get the part-coordinate position of an axis in current units.
If position is nil, reads the axis position from Mach4. For X and Y axes in Mill mode, uses mc.mcCntlGetValue() with VAL_G68_AXISPOS to account for G68 coordinate rotation. For all other axes, reads the SV_CURRENT_ABS_X + AxisID pound variable. If a position is explicitly provided, uses that value directly. For rotary axes (as determined by IsAxisRotary()), returns the position unchanged (no unit conversion). For linear axes, converts from setup units to current units via ConvertFromSetupUnits().
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.A_AXIS) |
| position | (number|nil) An optional pre-read position in setup units. If nil, reads from Mach4 |
| WrapperModule GetAxisSoftMaxLimitFromProfile | ( | AxisID | , |
| inst | ) |
Get the soft maximum limit for an axis in setup units, derived from the first mapped motor.
Retrieves the first motor mapped to the given axis via GetAxisChildMotorID(), then reads the motor's soft maximum limit in setup units via GetMotorSoftMaxLimitFromProfile(). Raises an error via w.Error() if no motors are mapped to the axis.
| AxisID | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetAxisSoftMinLimitFromProfile | ( | AxisID | , |
| inst | ) |
Get the soft minimum limit for an axis in setup units, derived from the first mapped motor.
Retrieves the first motor mapped to the given axis via GetAxisChildMotorID(), then reads the motor's soft minimum limit in setup units via GetMotorSoftMinLimitFromProfile(). Raises an error via w.Error() if no motors are mapped to the axis.
| AxisID | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCache | ( | category | , |
| entry_name | ) |
Retrieve a named entry from a cache category.
Ensures the cache category exists via w.VerifyCacheExists(), then returns the value stored at cat[entry_name]. Returns nil if the entry has not been set.
| category | (string) The cache category to read from |
| entry_name | (string) The entry key to retrieve within the category |
| WrapperModule GetCachedIoHandle | ( | inst | , |
| name | ) |
Get an I/O handle with per-instance caching.
Checks the I/O handle cache for the given instance and I/O path name. If a valid (non-zero, non-nil) cached handle exists, returns it immediately. Otherwise calls mc.mcIoGetHandle() to obtain a new handle, stores it in the cache, and returns it. If caching is disabled (w.MachHandles[inst].Cache is false), calls mc.mcIoGetHandle() directly without caching. Raises an error via w.Error() if the instance is out of range.
| inst | (number) The Mach4 instance handle (untagged, 0-5) |
| name | (string) The full I/O path (e.g., "MachMotion/MyIO") |
References name().
| WrapperModule GetCachedRegisterHandle | ( | inst | , |
| name | ) |
Get a register handle with per-instance caching.
Checks the register handle cache for the given instance and register path name. If a valid (non-zero, non-nil) cached handle exists, returns it immediately. Otherwise calls mc.mcRegGetHandle() to obtain a new handle, stores it in the cache, and returns it. If caching is disabled (w.MachHandles[inst].Cache is false), calls mc.mcRegGetHandle() directly without caching. Raises an error via w.Error() if the instance is out of range.
| inst | (number) The Mach4 instance handle (untagged, 0-5) |
| name | (string) The full register path (e.g., "MachMotion/MyRegister") |
References name().
| WrapperModule GetCachedSignalHandle | ( | inst | , |
| name | ) |
Get a signal handle with per-instance caching.
Checks the signal handle cache for the given instance and signal name. If a valid (non-zero, non-nil) cached handle exists, returns it immediately. Otherwise calls mc.mcSignalGetHandle() to obtain a new handle, stores it in the cache, and returns it. If caching is disabled (w.MachHandles[inst].Cache is false), calls mc.mcSignalGetHandle() directly without caching. Raises an error via w.Error() if inst is not a number or if the instance is out of range.
| inst | (number) The Mach4 instance handle (untagged, 0-5) |
| name | (number) The signal ID whose handle is to be retrieved |
References name().
| WrapperModule GetCalculatedAutoToolSetterPosition | ( | inst | ) |
Trigger an automatic tool setter measurement by executing M901.
Validates that an auto tool setter is configured via w.IsAutoToolSetterEnabled(). Raises an error if no auto setter is found. Otherwise, executes the "m901" MDI command via mc.mcCntlMdiExecute() to trigger the automatic tool measurement cycle.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCalculatedManualToolSetterPosition | ( | tool_setter_height | , |
| inst | ) |
Calculate the machine Z position of a manual tool setter for tool length measurement.
Validates that a manual tool setter is configured via w.IsManualToolSetterEnabled(). Raises an error if no manual setter is found. Reads the current Z machine position via mc.mcAxisGetMachinePos() and the current tool length offset via mc.mcCntlGetPoundVar(). If tool_setter_height is nil, resolves the current manual setter name and reads its height via GetToolSetterHeight(). Computes and returns: ZPosition - (ToolLengthOffset + tool_setter_height).
| tool_setter_height | (number|nil) The tool setter height to use. If nil, reads from the current manual setter configuration |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule debug GetCallStack | ( | start_frame | ) |
Return a multi-line string representation of the current Lua call stack.
Iterates over stack frames beginning at start_frame (default: 2, the immediate caller) and formats each frame as "[frame_idx] function_name(param_name(value), ...)". Function names are resolved via w.debug.GetFunctionName() using the function object cache. Parameter values are retrieved via w.debug.BriefParameterList(). Stops when debug.getinfo() returns nil.
| start_frame | (number|nil) The starting stack frame index. If nil, defaults to 2 (immediate caller) |
| WrapperModule GetCarouselCumulativeRotation | ( | axis | , |
| part_position | , | ||
| inst | ) |
Get the current cumulative rotation in degrees for a carousel axis.
Reads the current absolute axis position (which equals the cumulative rotation from zero) in either part or machine coordinates. Also computes the number of full rotations for informational logging. The cumulative rotation is the raw position value, not modulo 360.
| axis | (number) The axis ID constant for the carousel axis (e.g., mc.A_AXIS, mc.C_AXIS) |
| part_position | (boolean|nil) If true, reads part coordinates; if false or nil, reads machine coordinates |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCarouselRotationWithLimits | ( | axis | , |
| target_angle | , | ||
| part_position | , | ||
| inst | ) |
Calculate the optimal carousel rotation target considering cumulative rotation limits.
This is the main function to use for carousel tool changers with mechanical rotation limits. Reads the current axis position (cumulative rotation), determines candidate absolute target positions, evaluates both the direct path and the "go the other way" alternative path via IsCarouselPathViable() and CalculateCarouselPathScore(), then selects the best path. When scores are within 10% of each other, prefers the path that moves the cumulative rotation closer to zero. Returns the absolute axis position to command.
| axis | (number) The axis ID for the carousel (e.g., mc.A_AXIS, mc.B_AXIS, mc.C_AXIS) |
| target_angle | (number) The target angular position on the carousel (0-360 degrees) |
| part_position | (boolean|nil) If true, uses part coordinates; if false or nil, uses machine coordinates |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCommandDeviceName | ( | ) |
Return the device name string used for the Commands device.
Returns the fixed string "Commands", which is the device name under which all command registers and I/O points are registered.
| WrapperModule GetCommandFeedbackIOName | ( | name | ) |
Return the I/O name string for a command feedback entry in the Commands device.
Delegates to w.GetCommandFeedbackRegisterName() to produce the standardized I/O name used for feedback state I/O points registered under the Commands device.
| name | (string) The command feedback name to format |
References name().
| WrapperModule GetCommandFeedbackRegisterName | ( | name | ) |
Return the register name string for a command feedback entry in the Commands device.
Constructs the register name by prepending "[Feedback] " to the sanitized command name (via w.CleanUserCommandName()). This name is used to identify feedback state registers and I/O points under the Commands device.
| name | (string) The command feedback name to format |
References name().
| WrapperModule GetCommandFeedbackState | ( | command_table | ) |
Retrieve the current feedback state for a command based on its FeedbackSourceType.
Evaluates the command's feedback source according to its FeedbackSourceType field:
| command_table | (table) The command configuration table containing FeedbackSourceType, FeedbackSource, and related fields |
| WrapperModule GetCommandIOName | ( | name | ) |
Return the I/O name string for a command entry in the Commands device.
Delegates to w.GetCommandRegisterName() to produce the standardized I/O name used for command state I/O points registered under the Commands device.
| name | (string) The command name to format |
References name().
| WrapperModule GetCommandRegisterName | ( | name | ) |
Return the register name string for a command entry in the Commands device.
Constructs the register name by prepending "[Command] " to the sanitized command name (via w.CleanUserCommandName()). This name is used to identify command state registers and I/O points under the Commands device.
| name | (string) The command name to format |
References name().
| WrapperModule GetConfiguredGoToPosition_MachineZero | ( | inst | ) |
Retrieve the Machine Zero GoTo position configuration table if one is configured.
Checks whether a Machine Zero GoTo position exists via DoesExistGoToPosition_MachineZero(). If found, delegates to GetGoToPositionConfigurationFromSection() using the "GoTo_MachineZero" profile section to read all position data. Returns an empty table and false if not configured.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPosition_Park | ( | inst | ) |
Retrieve the Park GoTo position configuration table if one is configured.
Checks whether a Park GoTo position exists via DoesExistGoToPosition_Park(). If found, delegates to GetGoToPositionConfigurationFromSection() using the "GoTo_Park" profile section to read all position data. Returns an empty table and false if no park position is configured.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPosition_PartZero | ( | inst | ) |
Retrieve the Part Zero GoTo position configuration table if one is configured.
Checks whether a Part Zero GoTo position exists via DoesExistGoToPosition_PartZero(). If found, delegates to GetGoToPositionConfigurationFromSection() using the "GoTo_PartZero" profile section to read all position data. Returns an empty table and false if not configured.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPosition_ToolChange | ( | inst | ) |
Retrieve the Tool Change GoTo position configuration table if one is configured.
Checks whether a Tool Change GoTo position exists via DoesExistGoToPosition_ToolChange(). If found, delegates to GetGoToPositionConfigurationFromSection() using the "GoTo_ToolChange" profile section to read all position data. Returns an empty table and false if not configured.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPosition_ToolSetter | ( | inst | ) |
Retrieve the Tool Setter GoTo position configuration table if one is configured.
Checks whether a Tool Setter GoTo position exists via DoesExistGoToPosition_ToolSetter(). If found, delegates to GetGoToPositionConfigurationFromSection() using the "GoTo_ToolSetter" profile section to read all position data. Returns an empty table and false if not configured.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionGcode_MachineZero | ( | inst | ) |
Generate a G-code string for the configured Machine Zero GoTo position.
Retrieves the Machine Zero GoTo position configuration via GetConfiguredGoToPosition_MachineZero(). If a machine zero position is configured, delegates to GetGoToPositionGcodeFromTable() to generate the G-code string. Returns an empty string and the error message if no machine zero position exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionGcode_Park | ( | inst | ) |
Generate a G-code string for the configured Park GoTo position.
Retrieves the Park GoTo position configuration via GetConfiguredGoToPosition_Park(). If a park position is configured, delegates to GetGoToPositionGcodeFromTable() to generate the G-code string. Returns an empty string and the error message if no park position exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionGcode_PartZero | ( | inst | ) |
Generate a G-code string for the configured Part Zero GoTo position.
Retrieves the Part Zero GoTo position configuration via GetConfiguredGoToPosition_PartZero(). If a part zero position is configured, delegates to GetGoToPositionGcodeFromTable() to generate the G-code string. Returns an empty string and the error message if no part zero position exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionGcode_ToolChange | ( | inst | ) |
Generate a G-code string for the configured Tool Change GoTo position.
Retrieves the Tool Change GoTo position configuration via GetConfiguredGoToPosition_ToolChange(). If a tool change position is configured, delegates to GetGoToPositionGcodeFromTable() to generate the G-code string. Returns an empty string and the error message if no tool change position exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionGcode_ToolSetter | ( | inst | ) |
Generate a G-code string for the configured Tool Setter GoTo position.
Retrieves the Tool Setter GoTo position configuration via GetConfiguredGoToPosition_ToolSetter(). If a tool setter position is configured, delegates to GetGoToPositionGcodeFromTable() to generate the G-code string. Returns an empty string and the error message if no tool setter position exists.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositionNames | ( | inst | ) |
Get an ordered list of all configured GoTo position names.
Reads the GotoPositionsCount from the MachMotionControlPanel profile section and returns an array of position label strings for all configured GoTo positions. Positions with an empty label are omitted. The returned table is 1-indexed with consecutive integers.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredGoToPositions | ( | inst | ) |
Get the full configuration table for all configured GoTo positions.
Reads the GotoPositionsCount from the MachMotionControlPanel profile section and returns an array of position configuration tables, one for each configured GoTo position. Each entry is built by GetGoToPositionConfigurationFromIndex().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetConfiguredOperatorPanels | ( | ) |
Retrieve all configured operator panel entries from the Mach4 profile.
Reads the number of external controllers from the ExternalControllerData profile section, then iterates through each ExternalController{i} section to read the controller ID and look up its part number, device name, and description via GetOperatorPanelPartNumber(). Returns a table array of panel data entries plus a PartNumbers sub-table for fast part number lookup, a count field, and a GetOperatorPanel(PartNumber) accessor function.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetControlConfiguration | ( | ModelArray | ) |
Get the machine control configuration model number, dispatching to the correct schema version.
Checks the global SCREEN_VERSION variable and delegates to GetControlConfiguration_v1() for v1 screens or GetControlConfiguration_v2() for all other versions. Pass ModelArray as true to receive the model number components as an ordered array rather than a concatenated string.
| ModelArray | (boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string |
| WrapperModule GetControlConfiguration_v1 | ( | ModelArray | ) |
Build and return the machine model number string using v1 screen configuration.
Assembles the machine model number and model number array from globally configured control constants (CONTROL_SERIES_STR, CONTROL_REVISION_STR, etc.) using the v1 schema which includes CONTROL_SCREEN_STYLE_STR instead of CONTROL_SETUP_TIME. Loads version info, control configuration info, and machine type info. Determines software level, motion controller type, operator panel type, PLC type, OEM code, and custom code bits, then concatenates them into a formatted model number string. If ModelArray is true, returns the components as an array instead.
| ModelArray | (boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string |
| WrapperModule GetControlConfiguration_v2 | ( | ModelArray | ) |
Build and return the machine model number string using v2 screen configuration.
Assembles the machine model number and model number array from globally configured control constants using the v2 schema, which includes CONTROL_SETUP_TIME and uses a different software level mapping than v1. Loads version info, control configuration info, and machine type info. Determines software level, motion controller type, operator panel type, PLC type, OEM code, and custom code bits (by checking for UserGUIModule, UserMCodeModule, etc.), then concatenates them into a formatted model number string. If ModelArray is true, returns the components as an array instead.
| ModelArray | (boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string |
| WrapperModule GetControlLicensedModules | ( | License | ) |
Check whether a specific license module bit is active in the Mach4 control license.
Reads the full license bitmask via mc.mcCntlGetLicenseModules() and tests whether the specified License bit is set. Uses bitwise AND to isolate the bit and compares it to the expected power-of-two value.
| License | (number) The license module bitmask constant to check (e.g., mc.MC_LIC_PRO, mc.MC_LIC_LITE) |
| WrapperModule GetControlLicensedVersion | ( | ) |
Get the licensed version name of the Mach4 control software.
Checks which license modules are active via w.GetControlLicensedModules() and returns the corresponding software tier name. Checks for MachPro, Lite, and Educational licenses in order. If none match, defaults to "Demo".
| WrapperModule GetCurrentFixtureIndex | ( | inst | ) |
Get the current active fixture index (G54 = 1, G55 = 2, etc.).
Reads the VAL_FIXTURE_GP value from Mach4. If the value is an integer, the fixture index is computed as (value - 53), mapping G54 to 1, G55 to 2, etc. If the value is fractional (indicating an extended fixture offset), the secondary parameter is read and the index is computed as (secondary + 6) to represent extended fixture offsets beyond G59.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCurrentTool | ( | inst | ) |
Get the tool number currently loaded in the spindle.
If a user.GetCurrentTool override exists, delegates to it. Otherwise, reads the current tool number from Mach4: in Lathe mode reads SV_CUR_LENGTH_INDEX via mc.mcCntlGetPoundVar(); in Mill mode uses mc.mcToolGetCurrent().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCurrentToolPocket | ( | spindle | , |
| inst | ) |
Get the current tool pocket number from the configured memory source.
Delegates to user.GetCurrentToolPocket() if a user override exists. Otherwise, determines the memory source from the ToolChangerMemorySource OEM parameter. For PLC memory source (or Random Memory ATC), reads the pocket from the CurrentToolPocketRegister OEM register. For Mach memory source, reads the CurrentPocket attribute via GetToolChangeStatus(). Validates the pocket number is within the configured maximum range. Updates the CurrentToolPocket OEM register string on success.
| spindle | (number|nil) The spindle number to query. Defaults to the selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetCurrFileName | ( | caller_level | ) |
Get the source file name of the Lua script at the specified caller stack level.
Uses GetCurrFnName() to resolve the actual stack frame (skipping pcall and anonymous functions), then calls debug.getinfo() on the resolved level to retrieve the short source file name. Returns "(Unknown Script File)" if the caller or source cannot be determined.
| caller_level | (number|nil) The stack level to inspect. Defaults to 2 if not a number |
| WrapperModule GetCurrFnName | ( | caller_level | ) |
Get the function name of the Lua caller at the specified stack level, skipping pcall frames.
Walks the Lua call stack starting at caller_level, building a slash-delimited list of function names. Stops when a named function is found (that is not pcall) or when the top of the stack is reached. Anonymous or unnamed frames are represented as "(unknown)". Returns both the composed name string and the final stack level used, so callers can use the level to retrieve additional debug info for the same frame.
| caller_level | (number|nil) The starting stack level to inspect. Defaults to 2 if not a number |
| WrapperModule GetCurrLineNo | ( | caller_level | ) |
Get the current line number of the Lua source file at the specified caller stack level.
Uses GetCurrFnName() to resolve the actual stack frame (skipping pcall and anonymous functions), then calls debug.getinfo() on the resolved level to retrieve the current line number. Returns 0 if the caller or line number cannot be determined.
| caller_level | (number|nil) The stack level to inspect. Defaults to 2 if not a number |
| WrapperModule GetCustomCntlDwellBarValue | ( | ) |
Get the current value of the custom CNC dwell bar.
Reads and returns the numeric value of the CustomCntlDwellBar OEM parameter. A value of -1 typically indicates the dwell bar is inactive/stopped.
| WrapperModule GetDefaultCommand | ( | name | ) |
Return a default command configuration table for the given command name.
Constructs and returns a table with all standard command fields initialized to their default values. The Action is set to "Pre-Canned", FeedbackSourceType to "Pre-Canned", FeedbackTargetType to "Empty", and FeedbackCheckPeriod to 0.070 seconds. If name is nil or not a string, it defaults to an empty string.
| name | (string|nil) The command name. If nil, defaults to "" |
References name().
| WrapperModule GetDefaultSpindle | ( | inst | ) |
Get the default spindle number from the OEM parameters.
Reads the TC_DefaultSpindleNumber OEM parameter via w.eGetOEMParamValue() and returns it.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetDefaultUnitsModal | ( | ) |
Get the G-code modal string representing the machine's default unit system.
Reads the Mach4 setup units via GetMachSetupUnits() and returns the corresponding G-code modal: "G20" for imperial (200) or "G21" for metric (210). Returns an error if the setup units value is unrecognized.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetDriveEnable | ( | inst | ) |
Get the current state of the drive enable signal for the specified instance.
Checks whether the "DriveEnable" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, reads and returns its state via w.GetOEMParamSig(). If the signal is not mapped, returns false with a success status.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetFeatureKey | ( | feature | ) |
Return the numeric key for a named MachMotion license feature.
Looks up the given feature name in a local table of known feature keys and returns the associated integer key value. Returns nil if the feature name is not recognized. Known features: "MachMotion"=0, "GMS"=1, "Yaskawa"=2, "LatheCC"=3, "RMP"=4, "GrinderCC"=5.
| feature | (string) The feature name to look up (e.g., "MachMotion", "GMS", "Yaskawa") |
| WrapperModule GetFileQueueSleepTime | ( | ) |
Return the sleep interval in milliseconds used when polling the file queue for responses.
Returns a fixed value of 10 milliseconds, which is the polling interval used by w.WaitForFileQueueResponse() between successive checks for a reply.
| WrapperModule GetFixtureSetterAutoName | ( | inst | ) |
Get the currently selected auto fixture setter name.
Reads the AutoSetterFixtureSelection OEM parameter string. If the result is empty, falls back to reading the AutoSetterSelection OEM parameter instead.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetFixtureSetterManualName | ( | inst | ) |
Get the currently selected manual fixture setter name.
Reads the ManualSetterFixtureSelection OEM parameter string. If the result is empty, falls back to reading the ManualSetterSelection OEM parameter instead.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule debug GetFunctionName | ( | fn_obj | , |
| default | , | ||
| get_qualified_name | ) |
Look up the cached name for a function object.
Searches the internal __function_name_cache for an entry corresponding to fn_obj. Returns the unqualified name (e.g., "MyFunc") or qualified name (e.g., "w.MyFunc") depending on the get_qualified_name flag. Returns default if the function is not found in the cache.
| fn_obj | (function) The function object whose name is to be retrieved |
| default | (any) The value to return if fn_obj is not found in the cache |
| get_qualified_name | (boolean|nil) If true, returns the fully qualified name (e.g., "w.MyFunc"). If nil or false, returns the short name |
| WrapperModule GetG68PatchGcode | ( | inst | ) |
Get a G-code string to re-establish the current axis positions after G68 rotation.
Reads the IsG68PatchActive profile key from the MachMotion section. If the patch is active ("true"), calls GetGCodeToCurrentPosition() and returns the resulting G-code string. Returns an empty string if the G68 patch is not active or if an error occurs reading the profile key.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGCodeCNTL1MST | ( | inst | ) |
Get the current state of the G-code CNTL1 MST (suppress M/S/T waits) bit.
Reads the SV_CNTL1 pound variable via mc.mcCntlGetPoundVar() and returns the boolean state of bit 1, which controls whether Mach4 suppresses waits for M, S, and T codes.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGCodeErrorDescription | ( | ErrorNumber | ) |
Get a human-readable description for a G-code interpreter error number.
Looks up the given error number in an internal table of G-code error descriptions sourced from the Mach4 GCodeInterpreter.cpp source. The error number is incremented by 1 internally before lookup (0-based input). If the error number exceeds the table size, returns a "No Gcode Description Found" message. The table covers all standard RS274/NGC error codes including canned cycle, cutter compensation, arc, and macro errors.
| ErrorNumber | (number) The G-code error number to look up (0-based index) |
| WrapperModule GetGCodeToCurrentPosition | ( | inst | ) |
Build a G-code string with all enabled axis positions at the current location.
Generates a G-code position string (e.g., "X1.000 Y2.000 Z-5.000") for all enabled axes at their current absolute positions. In Lathe mode, covers X and Y axes only; in Mill mode, covers X and Y with G68 rotation compensation if active, and then Z through C axes for all modes. The Z axis value is unit-converted; rotary axes (A, B, C) are not converted.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGMSAlarms | ( | ) |
Check whether any GMS alarms are currently active.
Reads the "ActiveAlarm" I/O state from the GlobalMonitoringSystem device on instance 0 and returns it as a boolean. Returns nil and an error message if the I/O state cannot be read.
| WrapperModule GetGMSAlarmsAndWarnings | ( | ) |
Check whether any GMS alarms or warnings are currently active.
Calls w.GetGMSWarnings() and w.GetGMSAlarms() in sequence and returns true if either the ActiveWarning or ActiveAlarm I/O state is true. Returns false only if both are inactive. Propagates any errors from either sub-call.
| WrapperModule GetGMSClassName | ( | class | ) |
Get the display name string for a GMS message class.
Converts a class value to its display name string. Accepts either a numeric class code (0=Alarm, 1=Warning, 2=Notice, 3=Process) or a string class name. Returns the default class name ("Notice") if class is nil, out of range, or unrecognized. Uses w.GetGMSClassNumber() for string-to-number conversion.
| class | (number|string|nil) The class value to look up - either a numeric code or a string name such as "Alarm", "Warning", "Notice", or "Process" |
| WrapperModule GetGMSClassNumber | ( | class | ) |
Get the numeric class code for a GMS message class.
Converts a class value to its numeric representation. Accepts either a string class name (case-insensitive: "ALARM"=0, "WARNING"=1, "NOTICE"=2, "PROCESS"=3) or a numeric code. Returns the default class code (2, "NOTICE") if class is nil, out of range [0-3], or unrecognized.
| class | (number|string|nil) The class value to convert - either a numeric code or a string such as "Alarm", "Warning", "Notice", or "Process" |
| WrapperModule GetGMSHandleFromTitle | ( | title | ) |
Retrieve the GMS monitor handle for the first message found with the given title.
Sends a "FindTitle" command to the GMS plugin via w.SendGMSCommand() with the specified title string. Returns nil if no matching message is found (empty string or zero handle returned). The returned handle can be used with functions such as w.CloseGMSMessage() or w.UpdateGMSClass().
| title | (string|nil) The title text to search for. If nil or not a string, returns an error |
| WrapperModule GetGMSWarnings | ( | ) |
Check whether any GMS warnings are currently active.
Reads the "ActiveWarning" I/O state from the GlobalMonitoringSystem device on instance 0 and returns it as a boolean. Returns nil and an error message if the I/O state cannot be read.
| WrapperModule GetGoToPositionConfigurationFromIndex | ( | idx | , |
| inst | ) |
Get the GoTo position configuration table by zero-based index.
Constructs the profile section name "GotoPosition{idx}" and delegates to GetGoToPositionConfigurationFromSection() to read all configuration values for that position.
| idx | (number) The zero-based index of the GoTo position to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGoToPositionConfigurationFromName | ( | position_name | , |
| inst | ) |
Get the GoTo position configuration table by position name.
Reads the total GoTo position count from the MachMotionControlPanel profile section, then iterates through all configured positions looking for one whose Name matches position_name. Returns the matching configuration table on success, or an empty table and false on failure.
| position_name | (string) The name of the GoTo position to find (e.g., "ToolChange") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGoToPositionConfigurationFromSection | ( | section | , |
| inst | ) |
Read all GoTo position configuration values from a named profile section.
Reads all configuration keys for a GoTo position from the specified INI profile section, including position type flags (ToolChangePosition, ToolSetterPosition, PartZeroPosition, MachineZeroPosition, ParkPosition), machine coordinate mode, and multi-order axis positions (X/Y/Z/A/B/C position, order, XY tool offsets, and custom G-code) for each movement step. Iterates through sequentially numbered keys until a key is not found. Sets pos.MaxOrd to the highest valid order index found.
| section | (string) The profile section name to read from (e.g., "GotoPosition0", "GoTo_ToolChange") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGoToPositionGcode | ( | GoToMoveTypeName | , |
| MoveOrderName | , | ||
| GcodeHeader | , | ||
| inst | ) |
Build a complete G-code block for a named GoTo position move.
Constructs a G-code block by combining a safe-start string, an optional G68 rotation patch, and the position G-code from the named GoTo move type. For Mill machines, the safe-start string is "G50\nG90 G00"; for Lathe it is "G00". Applies the G68 patch if the IsG68PatchActive profile key is set to "true". Returns nil if the named position is not found or has no G-code.
| GoToMoveTypeName | (string) The name of the GoTo position to look up (e.g., "ToolChange", "Park") |
| MoveOrderName | (string|nil) Reserved for future use (currently unused) |
| GcodeHeader | (string|nil) Optional G-code header lines prepended before the safe-start string. Defaults to "" |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGoToPositionGcodeFromName | ( | position_name | , |
| inst | ) |
Generate a G-code string for a named GoTo position.
Looks up the GoTo position with the given name from all configured positions and returns the G-code string for that position via GetGoToPositionGcodeFromTable(). Returns an empty string if no position with the given name is found.
| position_name | (string) The name of the GoTo position to look up (e.g., "ToolChange") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetGoToPositionGcodeFromTable | ( | position_table | , |
| inst | ) |
Generate a G-code string for a multi-step GoTo position move from a position table.
Converts a GoTo position configuration table (as returned by GetGoToPositionConfigurationFromSection) into a G-code string. Handles machine coordinate offsets (G53), tool X/Y offsets, tool setter alignment offsets, and multi-order axis sequencing. Each order step is emitted as a separate G-code line with the appropriate axes. Custom G-code lines are supported via 'CustomActive' flags.
| position_table | (table) A GoTo position configuration table with keys for axis positions, orders, offsets, and flags. Must contain a 'MaxOrd' key or an error is raised. |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetHardwareEnable | ( | inst | ) |
Get the current state of the hardware enable signal for the specified instance.
Checks whether the "HardwareEnable" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, reads and returns its state via w.GetOEMParamSig(). If the signal is not mapped, returns false with a success status.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetInstanceCount | ( | ) |
Get the total number of active Mach4 instances, with caching.
Checks the "MachInstance" cache for the "Count" entry. If cached, returns the cached value immediately. Otherwise calls mc.mcCntlGetInstanceCount(), stores the result in the cache under "MachInstance"/"Count", and returns it.
| WrapperModule GetInstancesTable | ( | instance | ) |
Return a table of valid Mach4 instance numbers based on the input argument.
Converts various representations of instance selection into a normalized array of valid instance numbers. Behavior depends on the type of the instance argument:
| instance | (number|table|string|nil) The instance selection - nil for all, a number for one, a table for a subset, or a string representation of an integer |
| WrapperModule GetInstanceUnTaged | ( | inst | ) |
Return the untagged Mach4 instance number from a potentially tagged instance handle.
If inst is nil, retrieves the current instance via mc.mcGetInstance(). Strips the tag by masking with 0xFF (inst & 0xFF). Raises an error via w.Error() if the resulting instance number is outside the valid range [0, 5].
| inst | (number|nil) The Mach4 instance handle to untag. If nil, uses current instance |
| WrapperModule GetIoHandle | ( | inst | , |
| Device | , | ||
| IoName | ) |
Get a cached I/O handle for a device and I/O name.
Constructs the I/O path from Device and IoName (if IoName is non-nil), then delegates to w.GetCachedIoHandle() to retrieve or cache the handle. If IoName is nil, treats Device as the full path.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| Device | (string) The device name, or the full I/O path if IoName is nil |
| IoName | (string|nil) The I/O name to append to Device, or nil if Device is the full path |
| WrapperModule GetIoState | ( | Device | , |
| IoName | , | ||
| inst | ) |
Get the current state of an I/O point by device and name.
Gets the I/O handle via w.GetIoHandle() and reads the state via mc.mcIoGetState(). Returns an error if the device name or I/O name are not strings, if the I/O handle cannot be obtained, or if the mc.mcIoGetState() call returns a non-zero error code.
| Device | (string) The device name under which the I/O point is registered |
| IoName | (string) The name of the I/O point to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule Jogger GetJogMode | ( | ) |
Get the current jog mode of this Jogger instance.
Returns the numeric mode value representing the current jog mode: 0 = Continuous, 1 = Incremental, 2 = ABS, 3 = Feedrate.
| WrapperModule GetKeysSortedByValue | ( | tbl | , |
| sortFunction | ) |
Return an array of table keys sorted by their associated values.
Collects all keys from tbl into an array, then sorts the array using the provided sort function. If no sort function is provided, sorts in ascending order of associated values (i.e., the key whose value is smallest comes first).
| tbl | (table) The table whose keys are to be sorted by value |
| sortFunction | (function|nil) A comparator function(a, b) returning true if key a should come before key b. If nil, defaults to ascending value order |
References sortFunction().
| WrapperModule GetLastToolChangeStatus | ( | spindle | , |
| inst | ) |
Get the success or failure status of the last tool change operation.
Determines the tool changer memory source from the ToolChangerMemorySource OEM parameter. For PLC memory source, reads bit 63 from PLCMessages modbus register. For Mach memory source, reads the ToolChangeState attribute via w.GetToolChangeStatus(). Returns true if the last tool change was successful, false if it failed.
| spindle | (number|nil) The spindle number to check. Defaults to current selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetLocalVariable | ( | stack_frame | , |
| var_name | ) |
Return the value of a named local variable from a previous stack frame.
Iterates through local variables at the specified stack frame using debug.getlocal() until the variable named var_name is found, then returns its value. Returns nil if the variable is not found in that frame.
| stack_frame | (number) The stack frame index to inspect (1 = immediate caller, 2 = caller's caller, etc.) |
| var_name | (string) The name of the local variable to retrieve |
| WrapperModule GetMachBuild | ( | ) |
Get the Mach4 build number, with caching.
Checks whether w.MACH_BUILD has already been retrieved. If not, reads the "Build" register from the "core/global" device via w.GetRegValueLong() with a default of 0, stores the result in w.MACH_BUILD, and returns it. On subsequent calls, returns the cached value directly without a register read.
| WrapperModule GetMachineType | ( | inst | ) |
Get the current machine type and control mode information.
Reads the ControlMode profile integer from the 'DefaultMode' section and maps it to a human-readable description and a simplified mode string. Returns a table containing the description, control mode, and control type.
ControlMode mapping: 0 = Mill, 1 = Lathe (Diameter), 2 = Lathe (Radius), 3 = Tangental (Mill), 4 = 3D Printer (Mill), 5 = Laser (Mill), other = Unknown
| inst | (number) The Mach4 instance handle. If not provided, uses current selected instance |
| err GetMachInfo | ( | ) |
Format the Mach4 machine state information as a human-readable multi-line string.
Constructs a string from self.MachInfo containing the current machine state name and the loaded G-code file name. If a G-code file is loaded and the current line number is non-zero, also appends the G-code line number and line content.
| WrapperModule GetMachSetupUnits | ( | inst | ) |
Retrieve the setup unit system configured for the Mach4 machine profile.
Returns the cached value if previously read (via w.IsCached / w.GetCache). Otherwise, reads the SetupUnits key from the Preferences profile section via mc.mcProfileGetInt() with a default of -1. Raises a Lua error via w.Error() if the API call fails. Caches the result for subsequent calls. Returns 200 for imperial (inches) or 210 for metric.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMaximumJogFeedrate | ( | axis | , |
| inst | ) |
Get the maximum jog feedrate for an axis in setup units per minute.
Retrieves the result from cache if available. Otherwise reads the first motor mapped to the axis via mc.mcAxisGetMotorId() and calls GetMotorMaxVelocityFromProfile() to retrieve the motor's maximum velocity, which equals the axis maximum jog feedrate. Caches and returns the result.
| axis | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMaxToolNumber | ( | inst | ) |
Get the maximum number of tools configured in the Mach4 profile.
Reads the MaxTools key from the Preferences profile section via mc.mcProfileGetInt(). Returns 99 as the default if the key is not found. Raises an error via w.FunctionError() if the profile read returns a non-zero error code.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMaxToolPocketNumber | ( | spindle | , |
| inst | ) |
Get the maximum number of tool pockets configured for a spindle.
Reads the MaxNumberOfToolPockets OEM parameter via w.eGetOEMParamValueCached() for the specified spindle. If spindle is not a number, defaults to the currently selected spindle.
| spindle | (number|nil) The spindle number to query. Defaults to the selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMCodeHoldCount | ( | ) |
Get the current MCode hold counter value.
Reads and returns the current value of the MCodeHoldCount OEM register. A value greater than zero indicates that one or more hold requests are outstanding.
| WrapperModule GetmcSettingsDevice | ( | inst | ) |
Return the device path string for the Mach4 core settings device.
Returns the fixed string "core/settings" which is the device path used to access Mach4 core settings registers via the register API.
| err GetMessage | ( | ) |
Return the primary error message string from the error object.
Returns self.Message, which is the string originally passed to w.Error() when this error object was created.
| WrapperModule GetMinimumJogFeedrate | ( | axis | , |
| inst | ) |
Get the minimum jog feedrate for an axis in setup units per minute.
Retrieves the result from cache if available. Otherwise reads the first motor mapped to the axis via mc.mcAxisGetMotorId(), retrieves the motor's maximum velocity via GetMotorMaxVelocityFromProfile(), and multiplies it by the minimum jog rate percentage from GetMinimumJogRatePercentage(). Caches and returns the result.
| axis | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMinimumJogRatePercentage | ( | axis | , |
| inst | ) |
Calculate the minimum jog rate percentage for an axis based on motor encoder resolution.
Retrieves the result from cache if available. Otherwise reads the first motor ID mapped to the axis, retrieves counts-per-unit and maximum velocity from the profile, and calculates the minimum percentage as (1 / counts_per_ms) * 100, where counts_per_ms is derived from counts_per_unit * velocity / 60 / 1000. The result is clamped to a minimum of 0.05%. Caches and returns the result.
| axis | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotionController | ( | ) |
Retrieve the name of the currently configured motion controller device.
Reads the "MotionDevice" key from the "Preferences" section of the Mach4 profile. Returns "SimDev0" as the default if the key is not set.
| WrapperModule GetMotorCountsPerUnitFromProfile | ( | MotorID | , |
| inst | ) |
Get the counts-per-unit value for a motor from the Mach4 profile.
Reads the CountsPerUnit key from the Motor{MotorID} profile section via mc.mcProfileGetDouble() with a default of 1.0. Raises an error via w.Error() if the profile read fails.
| MotorID | (number) The motor ID whose counts-per-unit to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorMaxAccelFromProfile | ( | MotorID | , |
| inst | ) |
Get the maximum acceleration for a motor from the Mach4 profile in setup units per second squared.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then reads the MaxAccel key from the Motor{MotorID} profile section via mc.mcProfileGetDouble() with a default of 0.0. Returns the value divided by counts_per_unit to convert from counts/s² to setup units/s². Raises an error via w.Error() if the profile read fails.
| MotorID | (number) The motor ID whose maximum acceleration to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorMaxVelocityFromProfile | ( | MotorID | , |
| inst | ) |
Get the maximum velocity for a motor from the Mach4 profile in setup units per minute.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then reads the MaxVelocity key from the Motor{MotorID} profile section via mc.mcProfileGetDouble() with a default of 0.0. Returns the value divided by counts_per_unit multiplied by 60 to convert from counts/s to setup units/minute. Raises an error via w.Error() if the profile read fails.
| MotorID | (number) The motor ID whose maximum velocity to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorParentAxisID | ( | MotorID | , |
| inst | ) |
Find the axis ID that a given motor is mapped to.
Validates that MotorID is within the valid motor range, then iterates through all axes (0 to MC_MAX_AXES) and checks each motor slot via mc.mcAxisGetMotorId() to find a match. Returns the axis ID of the first axis that has MotorID in any of its motor slots, or returns an error if the motor is not mapped to any axis.
| MotorID | (number) The motor ID to find the parent axis for |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorPositionInSetupUnits | ( | MotorID | , |
| inst | ) |
Get the current motor position in setup units.
Reads the raw motor position in counts via w.api("mcMotorGetPos") and the counts-per-unit ratio via w.api("mcMotorGetCountsPerUnit"), then returns the quotient as the position in setup units.
| MotorID | (number) The motor ID to query |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorSoftMaxLimitFromProfile | ( | MotorID | , |
| inst | ) |
Get the soft maximum limit for a motor from the Mach4 profile in setup units.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then reads the SoftMaxLimit key from the Motor{MotorID} profile section via mc.mcProfileGetDouble() with a default of 0.0. Returns the value divided by counts_per_unit to convert from counts to setup units. Raises an error via w.Error() if the profile read fails.
| MotorID | (number) The motor ID whose soft maximum limit to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetMotorSoftMinLimitFromProfile | ( | MotorID | , |
| inst | ) |
Get the soft minimum limit for a motor from the Mach4 profile in setup units.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then reads the SoftMinLimit key from the Motor{MotorID} profile section via mc.mcProfileGetDouble() with a default of 0.0. Returns the value divided by counts_per_unit to convert from counts to setup units. Raises an error via w.Error() if the profile read fails.
| MotorID | (number) The motor ID whose soft minimum limit to retrieve |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule mcError GetMsg | ( | ) |
Return a human-readable error description string for a Mach4 error code.
Looks up the error code in the ErrorCodes table. If the code is not found, returns a message indicating an unrecognized error code. Otherwise, returns a formatted string combining the description, return code message name, and numeric code.
| errorcode | (number) The Mach4 error code to look up (e.g., mc.MERROR_NOERROR = 0) |
| WrapperModule mcError GetMsgCount | ( | ) |
Return the number of entries in the Mach4 error code table.
Calls w.GetTableCount() on WrapperModule.mcError.ErrorCodes to count the number of defined error code entries.
| WrapperModule GetNearestModValue | ( | value | , |
| mod_value | , | ||
| offset | ) |
Get the nearest modular boundary value (multiple of mod_value plus offset) to a given value.
Computes the lower and upper modular boundaries around value, finds the midpoint, and returns the lower boundary if value is below the midpoint, or the upper boundary otherwise.
| value | (number) The reference value to find the nearest boundary for |
| mod_value | (number) The modulus (interval size, e.g., 360 for rotary axes) |
| offset | (number) An additive offset applied to each interval boundary (e.g., a target angle) |
| WrapperModule GetNearestRotation | ( | axis | , |
| angle | , | ||
| part_position | , | ||
| inst | ) |
Get the nearest absolute position for a rotary axis to reach a target angle.
Reads the current axis position in either part or machine coordinates, then calls GetNearestModValue() to find the closest multiple of 360 degrees (plus the target angle offset) to the current position. This allows commanding a rotary axis to the nearest equivalent of the target angle without unnecessary full rotations. If part_position is true and the axis is an OB (auxiliary) axis, a Lua error is raised via w.Error().
| axis | (number) The axis ID constant (e.g., mc.A_AXIS, mc.B_AXIS, mc.C_AXIS) |
| angle | (number) The target angle in degrees (0-360). Defaults to 0 if nil; 360 is treated as 0 |
| part_position | (boolean|nil) If true, reads part coordinates; if false or nil, reads machine coordinates |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetNearestRotationFixedDirection | ( | axis | , |
| angle | , | ||
| part_position | , | ||
| inst | ) |
Get the nearest position on a fixed-direction rotary axis to a target angle, ensuring forward-only motion.
Similar to GetNearestRotation(), but when the current angle does not match the target within 0.01 degrees, it forces the result to the next modular boundary (via GetNextModValue()) rather than the nearest one. This ensures the axis only moves in the positive (forward) direction when seeking a target angle. If part_position is true and the axis is an OB (auxiliary) axis, a Lua error is raised via w.Error().
| axis | (number) The axis ID constant (e.g., mc.A_AXIS, mc.B_AXIS, mc.C_AXIS) |
| angle | (number) The target angle in degrees (0-360). Defaults to 0 if nil; 360 is treated as 0 |
| part_position | (boolean|nil) If true, reads part coordinates; if false or nil, reads machine coordinates |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetNetworkAdapters | ( | ) |
Retrieve the names and IP addresses of all network adapters on this machine.
Uses the LuaSocket library (require("socket")) to resolve the machine's hostname and look up its associated IP addresses. Each IP is returned as an entry in the adapters array with a generated name ("Adapter 1", "Adapter 2", etc.). Returns an empty table and an error string if the hostname or IP resolution fails.
| WrapperModule GetNextModValue | ( | value | , |
| mod_value | , | ||
| offset | ) |
Get the smallest multiple of mod_value (plus offset) that is strictly greater than value.
Computes the lower boundary of the modular interval containing value (via floor division plus offset), steps back one interval if the boundary exceeds value, then adds mod_value to get the next boundary above value.
| value | (number) The reference value |
| mod_value | (number) The modulus (interval size) |
| offset | (number|nil) An additive offset applied to each interval boundary. Defaults to 0 if nil |
| WrapperModule debug GetNextUsefulStackFrame | ( | starting_frame | ) |
Find the next stack frame index that has a meaningful function name.
Starting from starting_frame, steps forward through the call stack skipping frames whose name is nil or "pcall". Returns the first frame with a meaningful name, or starting_frame if no such frame is found before the top of the stack.
| starting_frame | (number) The stack frame index from which to begin searching |
| WrapperModule GetOEMParamDesc | ( | RegName | , |
| inst | ) |
Get the description string of an OEM parameter register.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), gets the register handle via w.GetRegHandle(), and reads the register description via mc.mcRegGetInfo(). Returns an error if the instance, device, or register name is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM parameter register to query |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamIOSigObject | ( | SigName | , |
| inst | ) |
Retrieve and cache the IOSig object referenced by an OEM parameter register string value.
Convenience wrapper that retrieves the OEM parameters device name via w.GetOEMParametersDevice() and delegates to w.GetParamIOSigObject() with that device.
| SigName | (string) The OEM parameter register name whose string value is the encoded IOSig path |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamReg | ( | ParamName | , |
| inst | ) |
Get the value of a register or analog signal pointed to by an OEM parameter register object.
Retrieves the register object associated with ParamName via w.GetOEMParamRegObject(). Depending on the object type, reads the value from the appropriate source: analog output via w.GetAnalogOutput(), analog input via w.GetAnalogInput(), or a standard register via w.GetRegValue(). Returns an error if the object cannot be retrieved or the read fails.
| ParamName | (string) The OEM parameter name whose register object points to the target register or analog signal |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamRegObject | ( | ParamName | , |
| inst | ) |
Retrieve and cache the register object referenced by an OEM parameter register string value.
Convenience wrapper that retrieves the OEM parameters device name via w.GetOEMParametersDevice() and delegates to w.GetParamRegObject() with that device.
| ParamName | (string) The OEM parameter name whose string value is the encoded register path |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamSig | ( | SigName | , |
| inst | ) |
Get the current state of a signal or I/O point referenced by an OEM parameter register.
Convenience wrapper that retrieves the OEM parameters device name via w.GetOEMParametersDevice() and delegates to w.GetParamSig() with that device.
| SigName | (string) The OEM parameter register name of the signal to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValue | ( | RegName | , |
| inst | ) |
Get the numeric value of an OEM parameter register.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), gets the register handle via w.GetRegHandle(), and reads the numeric value using mc.mcRegGetValue(). Returns an error if the instance, device, or register name is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValueBit | ( | ParamName | , |
| BitIdx | , | ||
| inst | ) |
Get the value of a specific bit from an OEM parameter.
Reads the current value of the OEM parameter identified by ParamName via w.GetOEMParamValue(), then extracts the bit at the zero-indexed position BitIdx using w.GetValueBit(). Passes through any errors from the parameter read or bit extraction.
| ParamName | (string) The name of the OEM parameter to read |
| BitIdx | (number) The zero-indexed bit position to extract |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValueBool | ( | RegName | , |
| inst | ) |
Get the value of an OEM parameter register as a boolean.
Reads the string value of the OEM parameter identified by RegName via w.GetOEMParamValueString(), then converts it to a boolean using w.ToBoolean(). Recognized string values include "true", "1", "yes", "on" (true) and "false", "0", "no", "off" (false).
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValueCached | ( | RegName | , |
| inst | ) |
Get the numeric value of an OEM parameter register with per-instance caching.
Checks the cache first using a category name derived from the untagged instance number and the register name. If cached, returns the cached value immediately. Otherwise reads the value via w.GetOEMParamValue(), stores it in the cache, and returns it.
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValueString | ( | RegName | , |
| inst | ) |
Get the string value of an OEM parameter register.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), gets the register handle via w.GetRegHandle(), and reads the string value using mc.mcRegGetValueString(). Returns an error if the instance, device, or register name is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMParamValueStringCached | ( | RegName | , |
| inst | ) |
Get the string value of an OEM parameter register with per-instance caching.
Checks the cache first using a category name derived from the untagged instance number and the register name. If cached, returns the cached value immediately. Otherwise reads the value via w.GetOEMParamValueString(), stores it in the cache, and returns it.
| RegName | (string) The name of the OEM parameter register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMRegValue | ( | RegName | , |
| inst | ) |
Get the numeric value of an OEM register.
Retrieves the OEM register device name via w.GetOEMRegisterDevice(), gets the register handle via w.GetRegHandle(), and reads the numeric value using mc.mcRegGetValue(). Returns an error if the instance, device, or register name is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMRegValueBit | ( | RegName | , |
| BitIdx | , | ||
| inst | ) |
Get the value of a specific bit from an OEM register.
Reads the current value of the OEM register identified by RegName via w.GetOEMRegValue(), then extracts the bit at the zero-indexed position BitIdx using w.GetValueBit(). Passes through any errors from the register read or bit extraction.
| RegName | (string) The name of the OEM register to read |
| BitIdx | (number) The zero-indexed bit position to extract |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetOEMRegValueString | ( | RegName | , |
| inst | ) |
Get the string value of an OEM register.
Retrieves the OEM register device name via w.GetOEMRegisterDevice(), gets the register handle via w.GetRegHandle(), and reads the string value using mc.mcRegGetValueString(). Returns an error if the instance, device, or register name is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| panels GetOperatorPanel | ( | PartNumber | ) |
Find a configured operator panel entry by part number.
Searches the panels table for the first entry whose PartNumber field matches the given PartNumber string. Returns the matching panel data table if found, or nil if not found. This is a closure defined inside GetConfiguredOperatorPanels() and attached to the returned panels table as panels.GetOperatorPanel.
| PartNumber | (string) The part number string to search for (e.g., "X15-10-01", "Software") |
| WrapperModule GetOperatorPanelPartNumber | ( | id | ) |
Look up operator panel hardware information by numeric ID.
Searches a static lookup table of known operator panel IDs and returns the matching entry containing the PartNumber, Device name, and Description. If the id is nil, non-numeric, or not found in the table, returns an empty table.
| id | (number) The numeric operator panel ID to look up (e.g., 1 for X15-10-01, 24 for Software) |
| WrapperModule GetParameter | ( | param | , |
| inst | ) |
Get the current value of a Mach4 control parameter and update the cache.
Verifies that the parameter exists via w.RequireParameterExist(), reads the current value via mc.mcCntlGetParameter() using the w.api() wrapper, and stores the result in the parameter cache via w.SetCache(). Returns the live value from the control.
| param | (number) The Mach4 control parameter number to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParameterBit | ( | param | , |
| bit | , | ||
| inst | ) |
Get the value of a specific bit from a Mach4 control parameter.
Reads the current value of the specified Mach4 control parameter via mc.mcCntlGetParameter() and extracts the bit at the given zero-indexed position using w.GetValueBit(). Updates the parameter cache with the current value. Returns 0 if the parameter has no value.
| param | (number) The Mach4 control parameter number to read |
| bit | (number) The zero-indexed bit position to extract from the parameter value |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParameterBitCached | ( | param | , |
| bit | , | ||
| inst | ) |
Get the value of a specific bit from a Mach4 control parameter, using cached values in screen chunks.
In screen chunk context (w.IsLuaRunningInScreenChunk() returns true), retrieves the parameter value from the cache via w.GetCache() and extracts the bit. Otherwise falls back to reading the parameter directly via mc.mcCntlGetParameter() and updating the cache. Returns the bit value as a number (0 or 1) via w.BoolToNumber().
| param | (number) The Mach4 control parameter number to read |
| bit | (number) The zero-indexed bit position to extract from the parameter value |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParameterCached | ( | param | , |
| inst | ) |
Get the value of a Mach4 control parameter, using cached values in screen chunks.
In screen chunk context (w.IsLuaRunningInScreenChunk() returns true) and when the value is already cached, returns the cached value directly without a Mach API call. Otherwise delegates to w.GetParameter() to read the live value from the control and update the cache.
| param | (number) The Mach4 control parameter number to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParameterCacheName | ( | param | , |
| inst | ) |
Return the cache category name string for a given Mach4 control parameter and instance.
Constructs the cache category name in the format "MachParameter[<inst>]" using the untagged instance number from w.GetUTI(). This name is used as the category key for all parameter cache operations.
| param | (number) The Mach4 control parameter number (used for context only; not included in the category name) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule debug GetParameters | ( | stack_frame | ) |
Retrieve all named local variables and their values from the specified stack frame.
Uses debug.getinfo() to determine the number of parameters for the function at stack_frame+1, then calls debug.getlocal() to retrieve each one by position. Skips internal Lua temporaries whose names begin with '('. Returns an empty table if the frame has no parameters or if the frame does not exist.
| stack_frame | (number) The stack frame to inspect, relative to the caller of this function |
| WrapperModule GetParamIOSigObject | ( | Device | , |
| SigName | , | ||
| inst | ) |
Retrieve and cache the IOSig object referenced by a parameter register string value.
Checks the cache first using a key combining Device, SigName, and untagged instance. If not cached, reads the encoded path string from the register via w.GetRegValueString(), validates it is non-empty and not "(nothing selected)", then parses it via w.ParseIOSigPath() using a protected call. Caches and returns the resulting IOSig object table.
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name whose string value is the encoded IOSig path |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParamRegObject | ( | Device | , |
| ParamName | , | ||
| inst | ) |
Retrieve and cache the register object referenced by a parameter register string value.
Checks the cache first using a key combining Device, ParamName, and untagged instance. If not cached, reads the encoded path string from the OEM parameter via w.GetOEMParamValueString(), validates it is non-empty and not "(nothing selected)", then parses it via w.ParseIOSigPath() using a protected call. Caches and returns the resulting object.
| Device | (string) The device name under which the parameter register is stored |
| ParamName | (string) The parameter register name whose string value is the encoded register path |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetParamSig | ( | Device | , |
| SigName | , | ||
| inst | ) |
Get the current state of a signal or I/O point referenced by a parameter register.
Retrieves the IOSig object for the parameter via w.GetParamIOSigObject(). Based on the object type, reads the state from the appropriate source:
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name of the parameter signal to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetPocketToolNumber | ( | , | |
| inst | ) |
Find the tool number currently assigned to a given pocket number.
Iterates through all tools up to the maximum tool number and checks the MTOOL_MILL_POCKET data field via mc.mcToolGetData() to find which tool number is assigned to the specified pocket. Returns 0 if no tool is found in the pocket, or if pocket is 0.
| (number) The pocket number to search for (1-based) | |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetPreCannedActionNames | ( | ) |
Retrieve the names of all registered pre-canned command action options.
Iterates over m.CommandActions using pairs() and collects all keys (action names) into an array table.
| WrapperModule GetPreCannedFeedbackNames | ( | ) |
Retrieve the names of all registered pre-canned command feedback options.
Iterates over m.CommandFeedbacks using pairs() and collects all keys (feedback names) into an array table.
| WrapperModule GetPreviousModValue | ( | value | , |
| mod_value | , | ||
| offset | ) |
Get the largest multiple of mod_value (plus offset) that is less than or equal to value.
Computes the lower boundary of the modular interval containing value: finds the floor multiple of mod_value and adds offset. If the result exceeds value, subtracts mod_value to step back one interval. Returns the lower boundary of the interval.
| value | (number) The reference value |
| mod_value | (number) The modulus (interval size) |
| offset | (number|nil) An additive offset applied to each interval boundary. Defaults to 0 if nil |
| WrapperModule GetPreviousTool | ( | inst | ) |
Get the previously active tool number.
Reads the PreviousTool attribute from the tool change status via w.GetToolChangeStatus(). Returns 0 on error.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetPreviousToolPocket | ( | spindle | , |
| inst | ) |
Get the previously active tool pocket number for a spindle.
Reads the PreviousPocket attribute from the tool change status via w.GetToolChangeStatus(). If spindle is not a number, defaults to the currently selected spindle. Returns 0 on error.
| spindle | (number|nil) The spindle number to query. Defaults to the selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetProbeFeedbackPositions | ( | positionnumber | ) |
Retrieve a stored probe feedback position value by position index.
Reads the OEM parameter named "ProbeFeedbackPosition_{positionnumber}" via w.GetOEMParamValue(). If the returned value equals the Mach4 nil pound variable (mc.mcCntlGetPoundVar(inst,0)), raises an error indicating the position was not set. Raises an error via w.Error() if the OEM parameter read fails.
| positionnumber | (number) The position slot index to read (0 through 5 inclusive) |
| WrapperModule GetProgrammedFeedRate | ( | ) |
Get the programmed feed rate in current units per minute.
Reads the SV_FEEDRATE pound variable via mc.mcCntlGetPoundVar(), which Mach4 reports in setup units. If the current unit system differs from the setup unit system, converts the feed rate to current units via w.ConvertUnits(). Caches the setup units and current units in module globals MACHINE_DEFAULT_UNITS and MACHINE_CURRENT_UNITS.
| WrapperModule GetRecentMachDir | ( | ) |
Get the most recently used Mach4 directory from MachMotion.ini.
Reads the 'Recent/MachDir' key from the MachMotion.ini file located in the roaming AppData directory. Uses a protected call internally; if an error occurs, logs a warning and returns 'C:\Mach' as a best-guess fallback. The ini file is read using wxFileConfig.
| WrapperModule GetRegDesc | ( | Device | , |
| RegName | , | ||
| inst | ) |
Get the description string of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and reads the register description using mc.mcRegGetInfo(). Returns an error if the device name or register name are not strings, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to query |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetRegHandle | ( | inst | , |
| Device | , | ||
| RegName | ) |
Get a cached register handle for a device and register name.
Constructs the register path from Device and RegName (if RegName is non-nil), then delegates to w.GetCachedRegisterHandle() to retrieve or cache the handle. If RegName is nil, treats Device as the full path.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| Device | (string) The device name, or the full register path if RegName is nil |
| RegName | (string|nil) The register name to append to Device, or nil if Device is the full path |
| WrapperModule GetRegValue | ( | Device | , |
| RegName | , | ||
| inst | ) |
Get the numeric value of a register.
-------------------— Register Wrappers ----------------------—
Gets the register handle for Device/RegName via w.GetRegHandle() and reads the value using mc.mcRegGetValue(). Returns an error if the device name or register name are not strings, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetRegValueLong | ( | Device | , |
| RegName | , | ||
| inst | ) |
Get the long integer value of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and reads the value using mc.mcRegGetValueLong(). Returns an error if the device name or register name are not strings, or if the register handle cannot be obtained. Use this instead of GetRegValue() when the register stores an integer value that must not be converted to a double.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetRegValueString | ( | Device | , |
| RegName | , | ||
| inst | ) |
Get the string value of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and reads the string value using mc.mcRegGetValueString(). Returns an error if the device name or register name are not strings, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetReloadCounter | ( | ) |
Retrieve the current value of the MachMotion configuration reload counter.
Reads and returns the value of the "mm_ConfigEndCounter" register in the MachMotion device. This counter is incremented each time a configuration reload occurs and can be polled to detect configuration changes.
| WrapperModule GetRotatedPartPos | ( | X | , |
| Y | , | ||
| InvertRotation | ) |
Calculate the rotated XY position accounting for G68 coordinate rotation.
Applies or inverts the G68 rotation transformation to the provided X and Y coordinates. If X or Y are nil or non-numeric, reads the current absolute machine position. The InvertRotation parameter controls the direction of rotation (1 for normal, -1 for inverse). Uses the rotation angle from mc.SV_ROTATION system variable.
| X | (number|nil) X coordinate to rotate. If nil or non-numeric, reads current machine X position |
| Y | (number|nil) Y coordinate to rotate. If nil or non-numeric, reads current machine Y position |
| InvertRotation | (number) Rotation direction: 1 for forward rotation, -1 for inverse. Clamped to these values |
| WrapperModule GetRotatedPosition | ( | x_machine | , |
| y_machine | , | ||
| angle | ) |
Calculate rotated coordinates using G68 rotation parameters.
Applies coordinate system rotation to the given X,Y position. If angle is not provided, retrieves the current rotation angle from the G68 system variable (mc.SV_ROTATION). Uses the standard G68 rotation convention (counter-clockwise positive).
| x_machine | (number) X coordinate in machine coordinate system |
| y_machine | (number) Y coordinate in machine coordinate system |
| angle | (number|nil) Rotation angle in degrees. If nil, retrieves from G68 system variable |
| WrapperModule GetSelectedInstance | ( | ) |
Get the currently selected Mach4 instance number.
Returns the cached value in WrapperModule.SELECTED_INST if it has been set (not nil and not -1). Otherwise calls w.UpdateSelectedInstance() to read and cache the value from the "core/global/SelectedInstance" register.
| WrapperModule GetSelectedSpindle | ( | inst | ) |
Get the currently selected spindle number.
Delegates to user.GetSelectedSpindle() if a user override exists. Otherwise, reads the TC_SelectedSpindleNumber OEM parameter via w.eGetOEMParamValue(). If the returned value is less than 1, falls back to the default spindle via GetDefaultSpindle().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetSelectedTool | ( | inst | ) |
Get the tool number currently selected (staged) for the next tool change.
If a user.GetSelectedTool override exists, delegates to it. Otherwise reads the selected tool from Mach4: in Lathe mode reads SV_CUR_LENGTH_INDEX via mc.mcCntlGetPoundVar(); in Mill mode uses mc.mcToolGetSelected().
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetSelectedToolPocket | ( | spindle | , |
| inst | ) |
Get the pocket number of the currently selected (staged) tool.
Delegates to user.GetSelectedToolPocket() if a user override exists. Otherwise, in Lathe mode reads the selected tool pocket via mc.mcToolGetSelected(). In Mill mode, reads the selected tool number via GetSelectedTool() and retrieves the MTOOL_MILL_POCKET data field for that tool via mc.mcToolGetData(). Returns 0 if no tool is selected.
| spindle | (number|nil) The spindle number to query. Defaults to the selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetSignalHandle | ( | inst | , |
| signal_id | ) |
Get a cached signal handle for a given signal ID.
Convenience wrapper that delegates directly to w.GetCachedSignalHandle() with the provided instance and signal ID.
| inst | (number) The Mach4 instance handle |
| signal_id | (number) The signal ID whose handle is to be retrieved |
| WrapperModule GetSignalInfo | ( | name | , |
| inst | ) |
Get detailed information about a signal by signal ID.
Gets the signal handle via w.GetSignalHandle(), retrieves signal attributes via mc.mcSignalGetInfo(), and also reads the user-defined description string from the Mach4 profile via mc.mcProfileGetString(). Returns a structured table with all signal properties. Returns an error if the signal name is not a number, if the signal handle cannot be obtained, or if either API call returns a non-zero error code.
| name | (number) The signal ID to query |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule GetSignalNumber | ( | inst | , |
| Device | , | ||
| Description | , | ||
| _debug | ) |
Search for a signal by description string within the specified signal device.
Iterates over all output signals (mc.MC_OSIGS_START to mc.MC_OSIGS_FINISH) or all input signals (mc.MC_ISIGS_START to mc.MC_ISIGS_FINISH) depending on the Device parameter, calling mc.mcSignalGetInfo() on each handle and comparing the description field to Description. Returns the signal ID of the first match found.
| inst | (number) The Mach4 instance handle |
| Device | (string) The signal category to search - must be "Output Signals" or "Input Signals" |
| Description | (string) The signal description string to search for |
| _debug | (any|nil) If non-nil, sets the Mach4 last error message with match progress for each signal checked |
| WrapperModule GetSignalState | ( | name | , |
| inst | ) |
Get the current state of a signal by signal ID.
-------------------— Signal Wrappers ----------------------—
Gets the signal handle via w.GetSignalHandle() and reads the state via mc.mcSignalGetState(). Returns an error if the signal name is not a number or if the signal handle cannot be obtained.
| name | (number) The signal ID to read |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule GetSignalUserDescription | ( | signal | ) |
Get the user-configured description for a signal, by name or signal ID.
Accepts either a signal name string or a numeric signal ID. If a string is given, attempts to resolve it first as an input signal, then as an output signal. Retrieves the signal info via mc.mcSignalGetInfo() and checks the profile for a user-defined description under the "Signal%i/UserDesc" key. If a user description is set, it is returned directly; otherwise the system description is returned. Returns a fallback "Description[signal]" string if the signal handle is not found.
| signal | (number|string) The signal ID number or signal name string to look up |
| WrapperModule GetSoftLimits | ( | inst | ) |
Get the current soft limits on/off state.
Reads the OSIG_SOFTLIMITS_ON output signal state via w.GetSignalState() to determine whether soft limits are currently enabled.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetTableCount | ( | T | ) |
Count the number of entries in a table, including non-integer keys.
Iterates over all key-value pairs using pairs() to count entries, including those with non-integer or non-sequential keys that the # operator would miss.
| T | (table) The table whose entries are to be counted |
| WrapperModule GetToleranceAmount | ( | level | , |
| amount | ) |
Get the tolerance amount for position comparisons based on level or explicit value.
Returns a tolerance value used for position comparisons. If amount is a number, it is used directly. Otherwise, the level string ('fine', 'standard', or 'coarse') selects from three predefined thresholds (0.0001, 0.001, 0.01 inches respectively). The selected tolerance is then converted from imperial to current units via ConvertFromImperialToCurrentUnits().
| level | (string|nil) The tolerance level: 'fine', 'standard', or 'coarse'. Defaults to 'standard' if nil |
| amount | (number|nil) An explicit tolerance value to use directly, bypassing the level lookup |
| WrapperModule GetToolChangerData | ( | inst | ) |
Read tool changer configuration data from the CSV and OEM parameters.
Delegates to user.GetToolChangerData() if a user override exists. Otherwise, reads the ToolChangerData.csv file from the profile's ToolTables directory using w.ReadCSV(). Parses the CSV into a pocket-indexed table keyed by the CSV header names. Also reads a predefined list of OEM parameters (TC_SensorTimeout, TC_DrawBarClampedInput, ZATCInterferanceZoneEnabled, etc.) and stores them in a Parameters sub-table. Returns a combined table with GetPocket() and GetParam() accessor methods.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolChangerInstance | ( | ) |
Get the Mach4 instance number to use for tool changer operations, with caching.
Checks the "MachInstance" cache for the "ToolChangerSingleInstance" entry. If cached, returns the cached value immediately. Otherwise reads the "ToolChangerSingleInstance" OEM parameter string via w.GetOEMParamValueString(). If the value is "Yes", returns 0 (instance 0 is always used for tool changer operations); otherwise returns the currently selected instance via w.GetSelectedInstance(). Caches and returns the result. Raises an error via w.Error() if the OEM parameter cannot be read.
| WrapperModule GetToolChangerOverride | ( | tool_number | , |
| inst | ) |
Get the tool changer override mode string for a given tool number.
Checks whether the ToolChangerMethod OEM parameter is "Auto". If not, returns "None" immediately since the override feature only applies to automatic tool changers. Otherwise, reads the ToolChangerOverride user field from the tool table for the specified tool number and returns "Manual" if the value equals the Manual override constant, or "None" otherwise.
| tool_number | (number) The tool number to check the override for |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolChangeStatus | ( | attribute | , |
| spindle | , | ||
| inst | ) |
Get a named tool change status attribute for a spindle.
Delegates to user.UserGetToolChangeStatus() if a user override exists. Otherwise, sends a GetAttribute command via w.RegSendCommand() to the MachMotion cmd_ToolChangeStatus register, formatted as "GetAttribute;{attribute};{spindle}". Returns an error if the attribute name is nil or not a string, or if the register command fails.
| attribute | (string) The name of the tool change status attribute to retrieve |
| spindle | (number|nil) The spindle number. Defaults to 1 if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolInfo | ( | ToolName | , |
| Attribute | ) |
Retrieve a specific attribute from the TOOL_NAMES configuration table by tool name.
Searches the TOOL_NAMES global table for an entry whose Name field matches ToolName, then returns the value of the specified Attribute key from that entry. If TOOL_NAMES is nil or empty, attempts to initialize it via CreateToolInfoFile(). Returns an error if ToolName is not a string, if the attribute is nil (Attribute parameter not provided), or if the name is not found in the table.
| ToolName | (string) The tool name to search for in the TOOL_NAMES table |
| Attribute | (string) The attribute key to retrieve from the matching tool entry (e.g., "Start", "End", "UseToolPocket") |
| WrapperModule GetToolName | ( | Number | ) |
Get the display name of a tool based on its tool number.
Looks up the tool name by searching the TOOL_NAMES table for a range entry where Number falls between Start and End (inclusive). If no matching range is found, returns the number as a string. If TOOL_NAMES is nil or empty, attempts to create it via CreateToolInfoFile(). If Number is nil, reads the current tool via mc.mcToolGetCurrent().
| Number | (number|nil) The tool number to look up. If nil, uses the currently active tool |
| WrapperModule GetToolSetter | ( | name | ) |
Retrieve a tool setter configuration table by name.
Calls w.GetAllToolSetters() to load all configured tool setters, then returns the entry whose key matches the given name. Returns nil if no tool setter with that name exists. Raises an error via w.Error() if name is nil or cannot be converted to a string.
| name | (string) The name of the tool setter to retrieve |
References name().
| WrapperModule GetToolSetterAutoName | ( | inst | ) |
Get the currently selected auto tool setter name.
Reads the AutoSetterSelection OEM parameter string via w.eGetOEMParamValueString() and returns it.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolSetterEndGoToPositionName | ( | ToolSetterName | ) |
Get the GoTo position name to move to after tool touchoff for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the EndGoToPosition field value.
| ToolSetterName | (string) The name of the tool setter whose end GoTo position to retrieve |
| WrapperModule GetToolSetterFixtureOffsetMode | ( | ToolSetterName | ) |
Get the fixture offset mode for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the FixtureOffsetMode field value. Returns 0 if the field is not set.
| ToolSetterName | (string) The name of the tool setter whose fixture offset mode to retrieve |
| WrapperModule GetToolSetterFixturesOffsets | ( | ToolSetterName | ) |
Check whether fixture offsets are enabled for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the FixturesOffsets field value.
| ToolSetterName | (string) The name of the tool setter to check |
| WrapperModule GetToolSetterGoToPositionName | ( | ToolSetterName | ) |
Get the GoTo position name to move to before tool touchoff for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the GoToPosition field value.
| ToolSetterName | (string) The name of the tool setter whose GoTo position to retrieve |
| WrapperModule GetToolSetterHeight | ( | ToolSetterName | ) |
Get the stored height value of a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the Height field value. Returns 0 if the tool setter is not found.
| ToolSetterName | (string) The name of the tool setter whose height to retrieve |
| WrapperModule GetToolSetterManualName | ( | inst | ) |
Get the currently selected manual tool setter name.
Reads the ManualSetterSelection OEM parameter string via w.eGetOEMParamValueString() and returns it.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolSetterPosition | ( | AutoManual | ) |
Get the stored Z position of a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the ZPosition field value.
| ToolSetterName | (string) The name of the tool setter whose Z position to retrieve |
| WrapperModule GetToolSetterPosition | ( | ToolSetterName | ) |
Get the stored Z position of a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the ZPosition field value.
| ToolSetterName | (string) The name of the tool setter whose Z position to retrieve |
| WrapperModule GetToolSetterProbeInput | ( | ToolSetterName | ) |
Get the probe input index for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the ProbeInput field value (0 = default probe, 1 = probe 1, 2 = probe 2, 3 = probe 3).
| ToolSetterName | (string) The name of the tool setter whose probe input index to retrieve |
| WrapperModule GetToolSetterProbeInputSignal | ( | ToolSetterName | ) |
Get the Mach4 signal constant for the probe input of a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the ProbeInputSignal field value (e.g., mc.ISIG_PROBE, mc.ISIG_PROBE1).
| ToolSetterName | (string) The name of the tool setter whose probe input signal to retrieve |
| WrapperModule GetToolSetterProbeName | ( | ToolSetterName | ) |
Get the G-code probe command name for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the ProbeName field value (e.g., "G31", "G31.1", "G31.2", "G31.3").
| ToolSetterName | (string) The name of the tool setter whose probe name to retrieve |
| WrapperModule GetToolSetterSoftlimitsEnabled | ( | ToolSetterName | ) |
Check whether soft limits are enabled for a named tool setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the logical inverse of the DisableSoftlimits field. Returns true if soft limits are enabled (DisableSoftlimits is false), false if they are disabled.
| ToolSetterName | (string) The name of the tool setter to check |
| WrapperModule GetToolSetterType | ( | ToolSetterName | ) |
Get the type string ("Auto" or "Manual") for a named tool setter.
Calls IsToolSetterAuto() for the given ToolSetterName and returns "Auto" if the setter is automatic, or "Manual" if it is a manual setter.
| ToolSetterName | (string) The name of the tool setter whose type to retrieve |
| WrapperModule GetToolTableFileName | ( | inst | ) |
Get the full file path to the active tool table file.
Constructs the path to the tooltable.tls file for the current Mach4 profile using MACH_DIRECTORY and the profile name. Initializes MACH_DIRECTORY and MACH_PROFILE_NAME_INST globals if they have not been set yet. Uses the UTI (unique tool instance) to look up the correct profile name for multi-instance configurations.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolTableUserValue | ( | fieldName | , |
| tool | , | ||
| inst | ) |
Get a numeric user field value from the tool table for a specified tool.
Wraps mc.mcToolGetDataExDbl() with error handling and instance management. If tool is nil, retrieves the current tool number via mc.mcToolGetCurrent(). Returns 0 and a success message if the tool number is 0 (no tool loaded).
| fieldName | (string) The name of the user field to read |
| tool | (number|nil) The tool number to read from. If nil, uses the current tool |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule GetToolTableUserValueString | ( | fieldName | , |
| tool | , | ||
| inst | ) |
Get a string user field value from the tool table for a specified tool.
Wraps mc.mcToolGetDataExStr() with error handling and instance management. If tool is nil, retrieves the current tool number via mc.mcToolGetCurrent(). Returns 0 and a success message if the tool number is 0 (no tool loaded).
| fieldName | (string) The name of the user field to read |
| tool | (number|nil) The tool number to read from. If nil, uses the current tool |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| err GetTraceback | ( | ) |
Format the error object's debug call stack as a human-readable multi-line string.
Iterates over self.DebugInfo (the stack frames captured at error creation time) and formats each frame as "function name(parameters) [source:line]". Parameters are extracted from the frame's Parameters table if present. Frames are separated by newlines.
| WrapperModule GetUnrotatedPosition | ( | x_machine | , |
| y_machine | , | ||
| angle | ) |
Calculate unrotated coordinates by reversing G68 rotation.
Applies inverse coordinate system rotation to convert from rotated to unrotated coordinates. The angle parameter should be the original rotation angle (not negated) - this function automatically negates it to perform the reverse transformation. If angle is not provided, retrieves the current G68 rotation angle and reverses it.
| x_machine | (number) X coordinate in rotated coordinate system |
| y_machine | (number) Y coordinate in rotated coordinate system |
| angle | (number|nil) Original rotation angle in degrees (will be negated internally). If nil, retrieves from G68 |
| WrapperModule GetUserCommand | ( | command_name | ) |
Retrieve a single user command configuration table by name.
Loads all user commands via w.GetAllUserCommands() and searches the resulting array for the first entry whose Name field matches command_name. Returns an empty table if no match is found.
| command_name | (string) The name of the user command to look up |
| WrapperModule GetUserCommandFilename | ( | command_name | ) |
Return the full file path for a named user command's INI file.
Constructs the path as: <UserCommandFolder><command_name>.ini
| command_name | (string) The name of the user command |
| WrapperModule GetUserCommandFolder | ( | ) |
Return the folder path where user command INI files are stored.
Constructs the path as: <MACH_DIRECTORY>\Profiles<MACH_PROFILE_NAME>\UserCommands
| WrapperModule GetUTI | ( | inst | ) |
Get the untagged Mach4 instance number (alias for GetInstanceUnTaged).
Convenience alias that delegates directly to w.GetInstanceUnTaged() with the provided inst parameter.
| inst | (number) The Mach4 instance handle (may be tagged). If not provided, uses current instance |
| WrapperModule GetValueBit | ( | value | , |
| BitIdx | ) |
Get the boolean value of the bit at a zero-indexed position in a value.
Extracts the bit at position BitIdx from value using a bitmask and returns it as a boolean. Returns 0 (false) if value is nil. Returns an error if BitIdx is outside the valid range [0, MAX_BITS).
| value | (number|nil) The integer value to extract the bit from. If nil, returns 0 |
| BitIdx | (number) The zero-indexed bit position to read (must be in [0, MAX_BITS)) |
| err GetVersionInfo | ( | ) |
Collect version information strings from the module table into the error object.
Iterates over the global 'm' table and collects all keys beginning with "VERSION_" into self.Versions for inclusion in error reports. Returns an empty string as this function is a side-effect-only collector.
| WrapperModule GetVersionInfo | ( | component | ) |
Get a specific component value from the loaded machine version information table.
Reads from the global MACH_VERSION_INFO table (populated by LoadVersionInfo()) and returns the value for the requested component name. Supports the following component names (case-insensitive): 'core_build', 'core_build_str', 'revision', 'revision_str', 'branch', 'version'. Returns nil if the component name is not recognized.
| component | (string) The version component to retrieve. One of: 'core_build', 'core_build_str', 'revision', 'revision_str', 'branch', 'version' |
| HandlerA | ( | ... | ) |
| WrapperModule HasModal | ( | Line | , |
| Modal | ) |
Check whether a G-code line contains a specific modal code.
Searches the given line string for the specified modal (G-code or M-code). Supports both integer modals (e.g., G0, G1, M3) and decimal modals (e.g., G43.1). Handles both uppercase and lowercase modal codes and leading zeros. Returns nil with an error if the modal prefix is not G or M, or if Modal or Line is nil.
| Line | (string) The G-code line string to search |
| Modal | (string) The modal code to search for (e.g., "G0", "G43.1", "M3") |
| WrapperModule IncrementCommandFeedbackUsage | ( | feedback_name | ) |
Increment the usage counter for a named command feedback in the Commands device register.
Looks up or creates the feedback register in the Commands device using the feedback register name. Reads the current value, increments it by 1, and writes the result back. Also increments the Value counter in m.CurrentActiveFeedbacks for the given feedback_name, creating the entry if it does not exist.
| feedback_name | (string) The name of the command feedback whose usage counter is to be incremented |
| WrapperModule IncrementCommandUsage | ( | command_name | ) |
Increment the usage counter for a named command in the Commands device register.
Looks up or creates the command register in the Commands device using the command register name. Reads the current value, increments it by 1, and writes the result back. Also increments the Value counter in m.CurrentActiveCommands for the given command_name, creating the entry with command data from w.GetUserCommand() if it does not exist.
| command_name | (string) The name of the command whose usage counter is to be incremented |
| WrapperModule IncrementMCodeHoldCount | ( | ) |
Increment the MCode hold counter by one.
Reads the current MCodeHoldCount OEM register value, adds one, then writes the updated value back.
| WrapperModule IncrementReloadCounter | ( | ) |
Increment the MachMotion configuration reload counter register.
Reads the current value of the "mm_ConfigEndCounter" register in the MachMotion device, increments it by 1, and writes the new value back. This counter is used to signal that a configuration reload has occurred so that other components can detect and respond to the change.
| WrapperModule InhibitJogOnAllAxes | ( | inst | ) |
Inhibit jogging on all axes (mc.AXIS0 through mc.MC_MAX_AXES-1).
Iterates through all axis IDs from mc.AXIS0 to mc.MC_MAX_AXES-1 and calls InhibitJogOnAxis() for each, incrementing each axis's jog inhibit counter by 1.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule InhibitJogOnAxis | ( | axis | , |
| inst | ) |
Increment the jog inhibit counter for a specific axis, preventing jogging.
Reads the InhibitJogAxis{axis} register from the MachMotion device, increments it by 1 (minimum 1), and writes the updated value back via SetRegValueLong(). The inhibit is reference-counted: jogging is blocked as long as the counter is greater than zero. Returns immediately without action if the axis is out of the valid range.
| axis | (number) The axis ID to inhibit jogging on (mc.AXIS0 through mc.MC_MAX_AXES-1) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule InhibitJogOnCoordinatedAxes | ( | inst | ) |
Inhibit jogging on all coordinated axes (mc.X_AXIS through mc.C_AXIS).
Iterates through axis IDs mc.X_AXIS through mc.C_AXIS and calls InhibitJogOnAxis() for each, incrementing each axis's jog inhibit counter by 1.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule InterpretRangeString | ( | range_string | ) |
Parse a range string of comma-delimited numbers and ranges into a flat array of integers.
Accepts a string consisting of individual integers and/or dash-separated ranges, separated by commas. Whitespace is stripped before parsing. Each comma-delimited piece is either a single integer (e.g., "5") or a range (e.g., "3-8"), which expands to all integers from start to finish inclusive. Leading/trailing commas and empty values are rejected with an error(). Out-of-order ranges (finish < start) are also rejected.
| range_string | (string) The range string to parse (e.g., "1,3-5,8" or "36" or "4,10-12,18") |
| WrapperModule IsAtGoToPositionFromName | ( | position_name | , |
| inst | ) |
Check whether all axes are at the named GoTo position within tolerance.
First verifies that all axes are homed via VerifyAllAxesAreHomedCached(). Then retrieves (and caches) the position configuration for the named GoTo position. For each axis from X to C, finds the most recent (highest-order) configured target position and checks whether the current machine or part position is within 0.01 units of the target. Returns false as soon as any axis is not within tolerance.
| position_name | (string) The name of the GoTo position to check (e.g., "ToolChange", "Park") |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsAutoToolSetterEnabled | ( | ) |
Check whether at least one automatic tool setter is configured.
Calls w.GetAllAutoToolSetters() to retrieve the count of configured auto tool setters and returns true if the count is greater than zero.
| WrapperModule IsAxisEnabled | ( | AxisID | , |
| inst | ) |
Check whether a specific axis is enabled in Mach4.
Validates that AxisID is a number within the valid axis range, then calls mc.mcAxisIsEnabled() to query the enabled state. Returns true if the axis is enabled, false if it is disabled. Returns an error via w.FunctionError() if the AxisID is invalid or if the API call returns a non-zero error code.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsAxisHomed | ( | AxisID | , |
| IgnoreSaftyCheck | , | ||
| inst | ) |
Check whether a specific axis is homed, respecting OEM homing safety parameters.
Validates the AxisID range and checks the HomingSafetyCheck OEM parameter. If homing safety is enabled (or IgnoreSaftyCheck is true), checks the IgnoreAxesHomingSafetyCheck parameter to see if the axis should be skipped. For axes with mapped motors, verifies the homed state via mc.mcAxisIsHomed(), calling MarkAxisAsHomedIfMotorsAreHomed() if needed. Returns true if the axis is homed, disabled, or excluded from the safety check.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to check |
| IgnoreSaftyCheck | (boolean) If true, forces the homing check regardless of the HomingSafetyCheck parameter |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsAxisInSideSoftLimitsZone | ( | AxisID | , |
| inst | ) |
Check whether the axis current machine position is within its soft limit zone.
Reads the soft limit enable state, max limit, min limit, and current machine position for the given axis via the Mach4 API. If soft limits are disabled (enabled == 0), returns true unconditionally. Otherwise, returns true only if the current position is within [min_limit, max_limit].
| AxisID | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsAxisMachinePositionInSideSoftLimitsZone | ( | AxisID | , |
| position | , | ||
| inst | ) |
Check whether a specified machine position is within the soft limit zone for an axis.
Reads the soft limit enable state, max limit, and min limit for the given axis. If soft limits are disabled (enabled == 0), returns true unconditionally. Otherwise, returns true only if the given position is within [min_limit, max_limit].
| AxisID | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| position | (number) The machine position to check against the soft limits |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsAxisPositionInToleranceMachine | ( | AxisID | , |
| RequestedPosition | , | ||
| Tolerance | ) |
Check whether the current axis machine-coordinate position is within tolerance of a requested position.
Reads the current machine position via w.api("mcAxisGetMachinePos") and returns true if the absolute difference between the current and requested positions is within Tolerance. Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| RequestedPosition | (number) The target machine position to compare against |
| Tolerance | (number|nil) The allowable position error. Defaults to w.GetToleranceAmount() if nil |
| WrapperModule IsAxisPositionInToleranceMachineLastOutput | ( | AxisID | , |
| RequestedPosition | , | ||
| Tolerance | ) |
Check whether an axis machine-coordinate position (last output) is within tolerance of a requested position.
Reads the last output machine position via the SV_LAST_OUTPUT_MACH_X + AxisID pound variable, then returns true if the absolute difference between the current and requested positions is within Tolerance. Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| RequestedPosition | (number) The target machine position to compare against |
| Tolerance | (number|nil) The allowable position error. Defaults to w.GetToleranceAmount() if nil |
| WrapperModule IsAxisPositionInTolerancePart | ( | AxisID | , |
| RequestedPosition | , | ||
| Tolerance | ) |
Check whether the current axis part-coordinate position is within tolerance of a requested position.
Reads the current absolute part position via the SV_CURRENT_ABS_X + AxisID pound variable using w.api(), then returns true if the absolute difference between the current and requested positions is within Tolerance. Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| RequestedPosition | (number) The target part-coordinate position to compare against |
| Tolerance | (number|nil) The allowable position error. Defaults to w.GetToleranceAmount() if nil |
| WrapperModule IsAxisPositionInTolerancePartLastOutput | ( | AxisID | , |
| RequestedPosition | , | ||
| Tolerance | ) |
Check whether an axis part-coordinate position (last output) is within tolerance of a requested position.
Reads the last output absolute part position via the SV_LAST_OUTPUT_X + AxisID pound variable, then returns true if the absolute difference between the current and requested positions is within Tolerance. Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| RequestedPosition | (number) The target part-coordinate position to compare against |
| Tolerance | (number|nil) The allowable position error. Defaults to w.GetToleranceAmount() if nil |
| WrapperModule IsAxisRotary | ( | AxisID | , |
| inst | ) |
Determine whether a given axis is a rotary (angular) axis.
Results are cached per instance under the key "IsAxisRotary_{inst}". For axes in the linear range (mc.X_AXIS through mc.A_AXIS - 1), always returns false without an API call. For other axes, calls mc.mcAxisGetRotary() and returns true if the result is 1 (rotary), false otherwise. Uses w.GetUTI() to normalize the instance.
| AxisID | (number) The axis ID constant to check (e.g., mc.X_AXIS, mc.A_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsCached | ( | category | , |
| entry_name | ) |
Check whether a named entry exists in a cache category.
Ensures the cache category exists via w.VerifyCacheExists(), then returns true if the entry at cat[entry_name] is not nil, or false if it is nil.
| category | (string) The cache category to check |
| entry_name | (string) The entry key to check within the category |
| WrapperModule IsCarouselPathViable | ( | current_cumulative_deg | , |
| movement_deg | ) |
Check whether a proposed carousel movement stays within the configured rotation limits.
Adds movement_deg to current_cumulative_deg to compute the final cumulative position, then checks whether its absolute value is within the usable limit (CAROUSEL_MAX_DEGREES minus CAROUSEL_SAFETY_MARGIN). Returns both the viability flag and the computed final cumulative position for use in path scoring.
| current_cumulative_deg | (number) The current cumulative rotation in degrees |
| movement_deg | (number) The proposed movement in degrees (positive=CW, negative=CCW) |
| WrapperModule IsCycleStartHoldActive | ( | ) |
Check whether a Cycle Start Hold is currently active.
Reads the mm_CycleStartMode register from the MachMotion device on instance 0. Returns true if the value is non-zero (hold active), false if zero (no hold).
| WrapperModule IsCycleStartPressedFlagSet | ( | ) |
Check whether the Cycle Start Pressed Flag is currently set.
Reads the CycleStartPressedFlag OEM parameter and returns true if the value is non-zero. The flag is set when Cycle Start is pressed while Mach is not idle and is automatically reset after the configured OnTime has elapsed.
| WrapperModule IsDebugging | ( | inst | ) |
Return whether MachMotion debugging mode is currently active.
Checks the "IsDebugging" OEM parameter string once and caches the result in WrapperModule.IsDebuggingActive for subsequent calls. Returns true if the parameter equals "Yes", false otherwise. The cached value persists for the lifetime of the session.
| inst | (number) The Mach4 instance handle (currently unused; always uses current instance internally) |
| WrapperModule IsEditorActive | ( | ) |
Check whether Mach4 is currently running in the editor.
Wraps mc.mcInEditor() to return a boolean indicating whether the Lua script is executing within the Mach4 built-in editor environment.
| WrapperModule IsFeatureLicensed | ( | feature_name | ) |
Check whether a named MachMotion feature is licensed via the plugin command register.
Sends a "CheckLicense;<feature_name>" request to the MachMotion plugin via the mm_LuaRequest register and interprets the response as a boolean. Returns false if the plugin command fails or if feature_name is nil. This function depends on the MachMotion plugin being present - command registers are harder to fake than anonymous DLLs.
| feature_name | (string|nil) The feature name to check (e.g., "MachMotion", "GMS"). If nil, returns false |
| WrapperModule IsGCodeFileLoaded | ( | inst | ) |
Check whether a G-code file is currently loaded in the specified instance.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsGCodeFileLoadedInAnotherInstance | ( | filename | , |
| inst | ) |
Check whether a given G-code file is already loaded in any other Mach4 instance.
Iterates over all available instances and compares the loaded G-code filename of each against the provided filename. Returns true as soon as a match is found in any instance.
| filename | (string) The full path to the G-code file to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsGeneralInput | ( | sig_id | ) |
Check whether a signal ID corresponds to a general input signal.
Looks up sig_id in the w.INPUT_NUMBERS table. Returns true if the signal ID is a known general input signal (i.e., the entry is non-nil), false otherwise.
| sig_id | (number) The signal ID to check |
| WrapperModule IsGeneralOutput | ( | sig_id | ) |
Check whether a signal ID corresponds to a general output signal.
Looks up sig_id in the w.OUTPUT_NUMBERS table. Returns true if the signal ID is a known general output signal (i.e., the entry is non-nil), false otherwise.
| sig_id | (number) The signal ID to check |
| WrapperModule IsGMSLicensed | ( | ) |
Check whether the GMS feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "GMS" feature.
| WrapperModule IsGrinderCCLicensed | ( | ) |
Check whether the GrinderCC feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "GrinderCC" feature.
| WrapperModule IsHardwareOperatorPanelEnabled | ( | ) |
Check whether at least one hardware (non-software, non-IOControl) operator panel is configured.
Calls GetConfiguredOperatorPanels() to retrieve all configured panels. Returns false immediately if no panels are configured. Otherwise iterates through the panels and returns true if any panel has a PartNumber that is not "Software" or "IOControl".
| WrapperModule IsHomeSwitchActive | ( | homing_axis | , |
| inst | ) |
Check whether a home switch is currently active for a specific axis or any axis.
If homing_axis is nil, checks all motors for an active home switch signal. If homing_axis is a valid axis ID, only checks motors mapped to that axis. Iterates through all motors (0 to MC_MAX_MOTORS-1) and reads each motor's home signal via GetSignalState(). Returns the axis ID of the first motor with an active home switch. Raises an error via w.Error() if homing_axis is non-nil and not a valid axis ID, or if signal retrieval fails.
| homing_axis | (number|nil) The axis ID to check, or nil to check all axes |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsInhibitJogOnAxis | ( | axis | , |
| inst | ) |
Check whether jogging is currently inhibited for a specific axis.
Reads the InhibitJogAxis{axis} register from the MachMotion device via GetRegValueLong() and returns true if the value is non-zero, false if zero.
| axis | (number) The axis ID to check (mc.AXIS0 through mc.MC_MAX_AXES-1) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule Jogger IsJogging | ( | ) |
Check whether the axis is currently jogging or in the process of stopping.
Queries mcJogIsJogging and mcJogIsStopping for this Jogger's axis and instance. Returns true if either indicates motion is ongoing.
| WrapperModule Jogger IsJogModeABS | ( | ) |
Check whether this Jogger is in ABS (absolute position) jog mode.
Returns true if the current jog mode is 2 (ABS mode).
| WrapperModule Jogger IsJogModeContinuous | ( | ) |
Check whether this Jogger is in continuous jog mode.
Returns true if the current jog mode is 0 (Continuous mode).
| WrapperModule Jogger IsJogModeFeedrate | ( | ) |
Check whether this Jogger is in feedrate jog mode.
Returns true if the current jog mode is 3 (Feedrate mode).
| WrapperModule Jogger IsJogModeIncremental | ( | ) |
Check whether this Jogger is in incremental jog mode.
Returns true if the current jog mode is 1 (Incremental mode).
| WrapperModule IsLatheCCLicensed | ( | ) |
Check whether the LatheCC feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "LatheCC" feature.
| WrapperModule IsLimitSwitchActive | ( | inst | ) |
Check whether any limit switch is currently active across all mapped motors.
Iterates through all 32 motor slots and checks both the plus and minus limit switch signals for each motor that is mapped to an axis. Motors with absolute encoders that are already homed are skipped. Uses GetSignalState() to read each limit signal. Returns the axis ID and enabled state of the first active limit switch found. Returns false with a completion message if all limit switches are clear.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsLuaRunningInMCodeChunk | ( | ) |
Check whether the current Lua execution context is an M-code chunk.
Checks the global LUA_CHUNK variable to determine if the currently executing Lua code is running inside an M-code macro chunk context.
| WrapperModule IsLuaRunningInScreenChunk | ( | ) |
Check whether the current Lua execution context is a screen chunk.
Checks the global LUA_CHUNK variable to determine if the currently executing Lua code is running inside a screen chunk context. This is important for functions that behave differently in screen vs M-code contexts (e.g., blocking wait functions that need to yield in screen chunks to prevent UI freezing).
| WrapperModule IsMachInitialized | ( | ) |
Check whether the MachMotion plugin has completed its initialization.
Sends an "is_initialized" request to the MachMotion plugin via w.RegSendCommand() on the "mm_LuaRequest" register and caches the result in w.__is_mach_initialized. Returns the cached result on subsequent calls without re-querying the plugin. Returns false if the plugin command fails.
| WrapperModule IsMachMotionLicensed | ( | ) |
Check whether the MachMotion base feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "MachMotion" feature.
| WrapperModule IsMachShuttingDown | ( | ) |
Check whether Mach4 is currently in the process of shutting down.
Returns true if the global MACH_SHUTTING_DOWN flag is set, or if the MachMotion/mm_ConfigEnd register cannot be retrieved (which indicates Mach is no longer fully operational). This is used to safely skip operations that should not run during shutdown.
| WrapperModule IsManualToolSetterEnabled | ( | ) |
Check whether at least one manual tool setter is configured.
Calls w.GetAllManualToolSetters() to retrieve the count of configured manual tool setters and returns true if the count is greater than zero.
| WrapperModule IsMCodeHoldActive | ( | ) |
Check whether an MCode hold is currently active.
Reads the MCodeHoldCount OEM register and returns true if the count is greater than zero, indicating that at least one hold request is outstanding.
| WrapperModule IsMotorMappedToAxis | ( | AxisID | , |
| MotorID | , | ||
| inst | ) |
Check whether a specific motor is mapped to a specific axis.
Validates both AxisID and MotorID ranges, then retrieves all motors mapped to AxisID via GetAxisChildMotorID(). Iterates through the returned motor array to check if MotorID is present. Returns true if the motor is found, false otherwise. Returns an error via w.FunctionError() if either parameter is invalid or out of range.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to check |
| MotorID | (number) The motor ID to look for on the axis |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsMultiInstance | ( | ) |
Check whether more than one Mach4 instance is running, with caching.
Checks the "MachInstance" cache for the "MultiInstance" entry. If cached, returns the cached value immediately. Otherwise calls w.GetInstanceCount() to retrieve the instance count, stores (count > 1) in the cache under "MachInstance"/"MultiInstance", and returns the result.
| WrapperModule IsOEMParamSigMapped | ( | SigName | , |
| inst | ) |
Check whether an OEM parameter signal register has a meaningful (non-empty) value mapped to it.
Convenience wrapper that retrieves the OEM parameters device name via w.GetOEMParametersDevice() and delegates to w.IsParamSigMapped() with that device.
| SigName | (string) The OEM parameter register name to check for a mapped signal or I/O |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsOperatorPanelJogging | ( | axis | ) |
Check whether the operator panel is actively jogging a specific axis.
Reads the JogState_{axis_letter} register from the OperatorPanelJoggers device via GetRegValueString(). Returns true if the jog state value is anything other than "INHIBIT", "IDLE", or "DISABLED", indicating the operator panel is currently jogging that axis.
| axis | (number) The axis ID constant to check (e.g., mc.X_AXIS). Used to look up the axis letter via AXIS_LETTER_ARRAY_0 |
| WrapperModule IsParamSigMapped | ( | Device | , |
| SigName | , | ||
| inst | ) |
Check whether a parameter signal register has a meaningful (non-empty) value mapped to it.
Checks the cache first using a key combining Device, SigName, and instance. If not cached, reads the register string value via w.GetRegValueString() and checks whether it is nil, empty, or "(nothing selected)". Caches and returns the result. Returns nil and an error if the register cannot be read.
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name of the parameter to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsProbeEnabledOutputOn | ( | inst | ) |
Check whether the probe enable output signal is currently active.
Checks whether the "ProbeEnableOutput" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, returns the current state via w.GetOEMParamSig(). If the signal is not mapped, returns true (indicating the probe output is assumed to be enabled).
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsProbeErrorInputOn | ( | inst | ) |
Check whether the probe error input signal is currently active.
Checks whether the "ProbeErrorInput" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, returns the current state via w.GetOEMParamSig(). If the signal is not mapped, returns false (indicating no probe error is present).
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsRMPLicensed | ( | ) |
Check whether the RMP feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "RMP" feature.
| WrapperModule IsSignalMapped | ( | Signal | , |
| inst | ) |
Check whether a signal is mapped to an I/O point.
Gets the signal handle via w.GetSignalHandle(), then retrieves the signal info struct via w.api("mcSignalGetInfoStruct"). Returns false if the sigMappedIoHandle field is nil or less than 1, indicating the signal is not mapped. Returns an error if the signal name is not a number or if the signal handle cannot be obtained.
| Signal | (number) The signal ID to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsSignalMappedAndEnabled | ( | Signal | , |
| inst | ) |
Check whether a signal is both mapped to an I/O point and enabled.
Gets the signal handle via w.GetSignalHandle(), then retrieves the signal info struct via w.api("mcSignalGetInfoStruct"). Returns false if the sigMappedIoHandle field is nil or less than 1, or if the sigEnabled field is nil or less than 1. Returns an error if the signal name is not a number or if the signal handle cannot be obtained.
| Signal | (number) The signal ID to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsSimMotionController | ( | ) |
Check whether the current motion controller is a simulator device.
Retrieves the motion controller device name via w.GetMotionController() and compares it against the known simulator device names "Sim0" and "SimDev0".
| WrapperModule IsSpindleSpeedVariationOn | ( | ) |
Check whether Spindle Speed Variation (SSV) is currently enabled.
Reads Mach4 parameter 1940 via the cached parameter getter to determine if Spindle Speed Variation is active. Uses a protected call internally to handle errors. If an error occurs during the check, logs the error and returns false.
| WrapperModule IsTableInRegister | ( | inst | ) |
Check whether a serialized Lua table is currently stored in the table register.
Reads the SendTableAcrossRegister OEM register string value. Returns true if the string is non-empty (indicating a table is waiting to be read), false if the register is empty.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolChangerOverrideOn | ( | tool_number | , |
| inst | ) |
Check whether a tool changer override is active for a given tool number.
Calls GetToolChangerOverride() and returns true if the result is not "None".
| tool_number | (number) The tool number to check |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolDrillTool | ( | tool | , |
| inst | ) |
Check whether the specified tool number belongs to a configured drill bank.
On mill machines, reads the number of configured drill banks and their tool number ranges from OEM parameters (TC_DrillBankNumberOfDrillBanks, TC_DrillBankRangeOfToolNumbersForDrillBank1/2). Interprets each range string and searches for the tool number within each bank. Returns false immediately for lathe machine types. Currently supports up to two drill banks.
| tool | (number) The tool number to check against configured drill banks |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolPathGenerating | ( | inst | ) |
Check whether the tool path is currently being generated for the specified instance.
Returns true if the machine is in dry run state, if the tool path generator is actively running, or if a G-code file is loaded and the tool path generation percentage is less than 100.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolSetterAuto | ( | ToolSetterName | ) |
Check whether a named tool setter is configured as an automatic setter.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter() and returns the AutoSetter field value.
| ToolSetterName | (string) The name of the tool setter to check |
| WrapperModule IsToolTableInitialized | ( | inst | ) |
Check whether the tool table file has been initialized with a valid structure.
First checks if the tool table file exists using w.FileExists(). If the file does not exist, returns false. If it does exist, opens the INI file and reads the 'Properties.Type' key. Returns true if the key is present (indicating a properly initialized tool table), or false if the key is not found.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolTableUserField | ( | fieldName | , |
| inst | ) |
Check whether a single user field name exists in the tool table file.
Opens the tool table INI file and reads the 'Properties.UsrFields' count, then iterates through all registered user field names looking for a match. Returns true if the field name is found, false otherwise. The INI reader is closed before returning.
| fieldName | (string) The user field name to search for in the tool table |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsToolTableUserFieldList | ( | field_list | , |
| inst | ) |
Check whether all field names in a list exist in the tool table file.
Opens the tool table INI file and reads the 'Properties.UsrFields' count, then for each field name in field_list, iterates through all registered user field names looking for a match. Returns false immediately on the first field name not found. If all field names are present, returns true. The INI reader is closed before returning.
| field_list | (table) A table whose keys are the user field names to check (e.g., {["FieldA"]={}, ["FieldB"]={}}) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule IsYaskawaLicensed | ( | ) |
Check whether the Yaskawa feature is licensed.
Convenience wrapper around w.IsFeatureLicensed() that checks for the "Yaskawa" feature.
| itself | ( | name will be auto- | discovered | ) |
Register a named function in this FunctionQueue group.
Adds a function to the queue's function list under the given name. If only a function is provided (no name), the function attempts to auto-discover the name by searching common module tables (m, m.screen, w, user). Non-function values are rejected with a log message.
References name().
| WrapperModule Jogger JogABS | ( | feedrate | ) |
Jog the axis to an absolute machine position at the specified feedrate.
Sets the Jogger to ABS mode (mode 2) if not already in that mode, calculates the effective feedrate via CalculateFeedrate(), then initiates an absolute position jog using mcJogAbsStart. Adjusts jog units to match setup units if a mismatch is detected (e.g., metric setup with imperial jog units). Acceleration is set to 100 before starting.
| position | (number) The absolute machine position to jog to |
| feedrate | (number) The commanded feedrate in units/minute. Clamped to min/max limits |
| WrapperModule Jogger JogABSWait | ( | feedrate | ) |
Jog the axis to an absolute position and block until the move is complete.
Calls JogABS() to initiate the absolute position jog, then calls Wait() to block execution until the axis has fully reached the target position and stopped.
| position | (number) The absolute machine position to jog to |
| feedrate | (number) The commanded feedrate in units/minute. Clamped to min/max limits |
| WrapperModule Jogger JogBasedOnMode | ( | ) |
Jog the axis using the current external jog mode and configuration parameters.
Reads the current ExternalContJogRate OEM parameter and clamps it to min/max limits. Sets the jog increment, acceleration, and rate from external jog configuration values before starting the jog. If the current mode is continuous (mode 0), uses mcJogVelocityStart; otherwise uses mcJogIncStart with the configured increment and direction.
| direction | (number|nil) The jog direction: 1 for positive, -1 for negative. Defaults to 1 if nil |
| WrapperModule Jogger JogIncremental | ( | increment | ) |
Jog the axis by a specified increment in the given direction.
Sets the Jogger to incremental mode (mode 1) if not already in that mode, then initiates an incremental jog move using mcJogIncStart. Sets the jog increment, acceleration, and rate before starting. The actual distance moved is increment multiplied by direction.
| direction | (number|nil) The jog direction: 1 for positive, -1 for negative. Defaults to 1 if nil |
| increment | (number) The distance to jog. Must not be nil or an error is raised |
| WrapperModule Jogger JogRotaryFeedrate | ( | feedrate | ) |
Jog the axis continuously at a feedrate in the specified direction.
Sets the Jogger to feedrate mode (mode 3) if not already in that mode, calculates the effective feedrate via CalculateFeedrate(), then starts a velocity jog using mcJogVelocityStart. The feedrate is clamped to external_jog_cont_rate and max_rate before being applied. Acceleration is set to 100 before starting the jog.
| direction | (number|nil) The jog direction: 1 for positive, -1 for negative. Defaults to 1 if nil |
| feedrate | (number) The commanded feedrate in units/minute. Clamped to min/max limits |
| WrapperModule Jogger JogStop | ( | ) |
Stop the axis velocity jog immediately.
Calls mcJogVelocityStop for this Jogger's axis and instance. This is a simple unconditional stop that does not check the current jog mode or whether jogging is active.
| WrapperModule Jogger JogVelocity | ( | rate | ) |
Jog the axis continuously at a specified rate in the given direction.
Sets the Jogger to continuous mode (mode 0) if not already in that mode, then starts a velocity jog using mcJogVelocityStart at the specified rate. The rate is clamped to min_rate from below before being applied. Acceleration is set via external_jog_accel.
| direction | (number|nil) The jog direction: 1 for positive, -1 for negative. Defaults to 1 if nil |
| rate | (number) The jog rate in units/minute. Clamped to min_rate from below and max_rate from above |
| w JoinArgs | ( | _args | , |
| "; " | , | ||
| 2 | ) |
Join variadic arguments into a delimited string.
Converts a packed argument table (from table.pack(...)) into a single string with specified delimiter. The args table must have an 'n' field (the count) as created by table.pack(). All arguments are converted to strings before concatenation. Useful for formatting variadic function parameters for logging or display.
| args | (table) Packed argument table with 'n' field (from table.pack(...)) |
| delim | (string|nil) Delimiter between arguments. If nil, defaults to "; " |
| start_index | (number|nil) Starting index (1-based). If nil, defaults to 1 |
| WrapperModule JoinArgs | ( | args | , |
| delim | , | ||
| start_index | ) |
Join variadic arguments into a delimited string.
Converts a packed argument table (from table.pack(...)) into a single string with specified delimiter. The args table must have an 'n' field (the count) as created by table.pack(). All arguments are converted to strings before concatenation. Useful for formatting variadic function parameters for logging or display.
| args | (table) Packed argument table with 'n' field (from table.pack(...)) |
| delim | (string|nil) Delimiter between arguments. If nil, defaults to "; " |
| start_index | (number|nil) Starting index (1-based). If nil, defaults to 1 |
| WrapperModule table key_to_str | ( | k | ) |
Convert a table key to a compact string for use in table.repr() output.
If the key is a plain string identifier (matching ^[_a][_ad]*$), returns the key directly. Otherwise, wraps the key in brackets using val_to_str() so that it can be used as a valid Lua table key expression.
| k | (any) The table key to convert |
| WrapperModule table pretty key_to_str | ( | k | , |
| indent | ) |
Convert a table key to an indented string for use in pretty-printed output.
If the key is a plain string identifier (matching ^[_a][_ad]*$), returns the key prefixed with the indent string. Otherwise, wraps the key in brackets using val_to_str() for safe representation of non-identifier keys.
| k | (any) The table key to convert to a string |
| indent | (string|nil) The indentation prefix string. Defaults to "" if nil |
| WrapperModule LLLog | ( | logfile | , |
| msg | , | ||
| ... ) |
Write a timestamped log message with stack traceback to a file.
Opens the specified log file in append mode and writes a formatted entry containing the current clock time, the formatted message string, and a full Lua debug traceback. If logfile is nil, defaults to "wrapper.log". The message and additional arguments are formatted via string.format().
| logfile | (string|nil) The log file path to append to. If nil, defaults to "wrapper.log" |
| msg | (string) The format string for the log message (passed to string.format()) |
| ... | (any) Additional arguments for string.format() applied to msg |
| WrapperModule Load | ( | basename | , |
| path_dir | , | ||
| force | ) |
Load a named Lua module from a subdirectory of the Mach installation directory.
Searches for a file named basename with extension .lua, .mcs, or .mcc (in that order) under MACH_DIRECTORY/path_dir/. Logs the result and updates package.path to include the target directory. If force is true, clears the module from package.loaded to ensure a fresh load. Calls require(basename) to load and return the module. Returns nil if no matching file is found.
| basename | (string) The module name (without extension) to load |
| path_dir | (string|nil) The subdirectory path relative to MACH_DIRECTORY. Defaults to '' if nil |
| force | (boolean|nil) If true, forces a reload by removing the module from package.loaded first |
| WrapperModule LoadGCodeFile | ( | filename | , |
| inst | ) |
Loads a GCode file into the specified instance.
It first checks if the instance is valid and retrieves the current instance. It then runs any hooks associated with loading a GCode file. If the machine is not idle, it raises a warning and an error. Depending on the OEM parameter "EnableGCAdapter", it either adapts the file using the GCAdapter or directly loads the GCode file into the instance. It also handles tool path generation and ensures the instance is restored to its original state after loading the file.
| filename | The path to the GCode file to load. |
| inst | The instance number to load the file into. If not provided, the current instance is used. |
| inst | The instance number to load the file into. If not provided, the current instance is used. |
| WrapperModule LoadOpStatus | ( | force | ) |
Load the OpStatus module if it has not already been loaded.
Attempts to load the OpStatus module from two possible paths: 'Modules/Addons/operational_status' and 'Modules/Addons', using w.Load(). Stores the result in w.OpStatus. If w.OpStatus is already non-nil, no loading is attempted. The force parameter is passed to w.Load() to control whether the module is reloaded even if already in package.loaded.
| force | (boolean|nil) If true, forces the module to reload even if already loaded. Defaults to false |
| WrapperModule LoadVersionInfo | ( | ) |
Load the machine version information from the MachBuildVer.lua file into a global table.
Reads the MachBuildVer.lua file from the VersionInfo directory in the Mach installation, evaluates it as a Lua expression via w.EvaluateLuaExpression(), and stores the resulting data table in the global MACH_VERSION_INFO. The table contains: core_build (number), core_build_str (string), revision (number), revision_str (string), branch_str (string), and version_str (string).
| WrapperModule Log | ( | CustomMessage | , |
| FileName | , | ||
| LineNumber | , | ||
| CallerLevel | , | ||
| inst | ) |
Write a message to the Mach4 log and the MachMotion.log file with caller context.
Resolves the caller's source file and line number from the Lua debug stack (using CallerLevel if provided, otherwise level 2). Formats and sends the message to mc.mcCntlLog() and also appends it to the MachMotion.log file via _log_to_file(). The file name portion of the source path is extracted for brevity. If CallerLevel is provided, that level is used directly so library wrapper functions can attribute the log entry to their own caller.
| CustomMessage | (string) The message to log. Non-string values are converted with tostring() |
| FileName | (string|nil) Override source file name. If nil, resolved from the debug stack |
| LineNumber | (number|nil) Override line number. If nil, resolved from the debug stack |
| CallerLevel | (number|nil) The debug stack level to use for context resolution. Defaults to 2 |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule LogC | ( | ... | ) |
Log all provided values concatenated into a single space-delimited message.
Iterates through all variadic arguments using select() and concatenates each value (converted via tostring()) into a single space-delimited string, then passes it to w.Log(). Useful for quickly logging multiple values without manual string formatting.
| ... | (any) Variable number of values to log. Each is converted with tostring() |
| WrapperModule LogF | ( | fmt | , |
| ... ) |
Log a printf-style formatted message using string.format().
Calls string.format(fmt, ...) and passes the result to WrapperModule.Log() at caller level 3 so the log entry is attributed to the caller of LogF rather than to LogF itself.
| fmt | (string) A string.format() format string |
| ... | (any) Arguments to substitute into the format string |
| WrapperModule LogMultiline | ( | message | , |
| indent | ) |
Log a multi-line message by splitting on newlines and logging each line separately.
Splits message on "\n" using WrapperModule.string.split() and calls WrapperModule.Log() for each resulting line, prepending the indent string. If indent is nil, no indentation is applied. Each line is logged at caller level 3 so that the log entry is attributed to the caller of LogMultiline rather than to LogMultiline itself.
| message | (string) The multi-line message to log |
| indent | (string|nil) An optional prefix string prepended to each line. Defaults to "" if nil |
| WrapperModule LogoutPassword | ( | ) |
Clear the stored password session so the user must re-enter their password.
Deletes the LastPassword and LastPasswordClock keys from the MachMotionControlPanel profile section, invalidating any active stay-logged-in password session.
| WrapperModule MakeDirectory | ( | Path | ) |
Create the target directory and all nonexistent ancestor directories.
WrapperModule.MakeDirectory
Create the target directory and all nonexistent ancestor directories.
| WrapperModule MakeNewFileQueue | ( | ) |
Create and return a new LuaFileQueue instance for the current Mach directory.
Retrieves the input and output file paths for the Lua file queue using lfq.GetLuaPaths(MACH_DIRECTORY), then constructs and returns a new lfq queue object.
| WrapperModule MapMotorsToAxis | ( | AxisID | , |
| MotorID | , | ||
| inst | ) |
Map a motor to an axis, enabling the axis and unmapping the motor from any prior axis.
If the motor is already mapped to another axis, it is first unmapped from that axis via mc.mcAxisUnmapMotor(). If the target axis is disabled, it is enabled via mc.mcAxisEnable(). The motor is then mapped to the specified axis via mc.mcAxisMapMotor(), and mc.mcMotionSync() is called to synchronize the motion controller. If the motor is already mapped to the correct axis, the function returns early without making changes. Raises an error via w.Error() if AxisID or MotorID are nil or out of range.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to map the motor to |
| MotorID | (number) The motor ID to map to the axis |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule MarkAxisAsHomedIfMotorsAreHomed | ( | AxisID | , |
| inst | ) |
Mark an axis as homed if all of its mapped motors report as homed.
First checks if the axis is already homed via mc.mcAxisIsHomed() and returns immediately if so. Otherwise, retrieves all motors mapped to the axis via GetAxisChildMotorID() and checks each motor's homed state via mc.mcMotorIsHomed(). If all motors are homed and the axis is enabled, calls mc.mcAxisHomeComplete() to mark the axis as homed in Mach4.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to check and potentially mark as homed |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule MCodeError | ( | msg | , |
| filename | , | ||
| line | ) |
Construct and raise a Mach4 M-code error with macro context information.
Creates an enriched error object via w.pcall(w.Error, msg), then overwrites the Traceback and DebugInfo fields with the provided macro filename and line number. This ensures that error reporting shows the M-code file context rather than the Lua stack context. Unlike functions that return error status, this function NEVER returns - it always raises an exception.
| msg | (string) The error message to include in the exception |
| filename | (string|nil) The M-code source file where the error occurred |
| line | (number|nil) The line number in the M-code file where the error occurred |
| WrapperModule MDICommand | ( | Command | , |
| PushPop | , | ||
| Message | , | ||
| OverrideDisable | , | ||
| inst | ) |
Execute an MDI command on the selected instance with an optional Please Wait dialog.
Validates that the machine is enabled and that Command is a valid string, then optionally pushes machine state (if PushPop is true), executes the command via w._MDICommand() with NoDialog=false (showing a PleaseWaitDialog), and optionally pops machine state. Uses w.pcall() for error protection. The Please Wait dialog displays until the machine returns to IDLE.
| Command | (string) The G-code or MDI command string to execute |
| PushPop | (boolean|nil) If true, saves and restores machine state around the command |
| Message | (string|nil) Status message for the Please Wait dialog. Defaults to "Please wait..." if nil |
| OverrideDisable | (boolean|nil) If true, prevents machine disable when the dialog cancel button is pressed |
| inst | (number|nil) The Mach4 instance handle. If nil, uses the selected instance |
| WrapperModule MDICommandNoDialog | ( | Command | , |
| PushPop | , | ||
| Message | , | ||
| OverrideDisable | , | ||
| inst | ) |
Execute an MDI command on the selected instance without displaying a confirmation dialog.
Validates that the machine is enabled and that Command is a valid string, then optionally pushes machine state (if PushPop is true), executes the command via w._MDICommand() with NoDialog=true, and optionally pops machine state. Uses w.pcall() for error protection. Unlike MDICommand(), this function does not show a "Please Wait" dialog - it uses WaitOnCondition directly to wait for the machine to return to IDLE.
| Command | (string) The G-code or MDI command string to execute |
| PushPop | (boolean|nil) If true, saves and restores machine state around the command |
| Message | (string|nil) Status message to display while waiting. Defaults to "Please wait..." if nil |
| OverrideDisable | (boolean|nil) If true, prevents machine disable on cancel |
| inst | (number|nil) The Mach4 instance handle. If nil, uses the selected instance |
| WrapperModule Averager mean | ( | ) |
Calculate the arithmetic mean of all sampled y-values in the current window.
Sums all stored data points and divides by the count. Returns 0 if no points have been sampled yet. This is the simple running average without trend compensation.
| WrapperModule Averager mean_x | ( | ) |
Calculate the mean of the x-index sequence for the current sample window.
Because the x-indices form a simple integer sequence (1, 2, ..., n), the mean can be computed analytically as (n+1)/2 rather than by iterating through all values. This is used internally by the trend and regression calculations.
| WrapperModule table merge | ( | t1 | , |
| t2 | ) |
Merge table t2 into table t1, preferring entries from t2 on conflict.
Recursively merges all key-value pairs from t2 into t1. If both t1 and t2 have a table value for the same key, the tables are merged recursively. For all other value types, t2 overwrites t1. t1 is modified in place and also returned. If t2 is nil, the function returns immediately without modifying t1.
| t1 | (table) The target table to merge into. Must not be nil |
| t2 | (table|nil) The source table to merge from. If nil, no changes are made |
| WrapperModule MessageBox | ( | message | , |
| ... ) |
Display a modal message box and restore the Mach4 instance context on return.
Synonym for w.wxMessageBox(). Delegates directly to WrapperModule.wxMessageBox() with all provided arguments.
| message | (string) The message text to display in the dialog |
| ... | (any) Additional arguments passed to wx.wxMessageBox() (e.g., caption, style, parent) |
| WrapperModule MessageDialog | ( | Message | , |
| Title | , | ||
| DialogType | ) |
Display a modal dialog with a message and configurable button layout.
Creates and shows a modal dialog appropriate to the current execution context. In M-code chunk context (MAIN_LUA_MACRO_CHUNK_ACTIVE set), uses a standard wx.wxMessageDialog. In screen chunk context, creates a styled MachMotion dialog with standard formatting. Supports four dialog types: "OK", "OKCancel", "YesNo", and "Continue"/"Cancel". Returns the name of the button that was pressed.
| Message | (string) The message text to display in the dialog body |
| Title | (string) The dialog window title |
| DialogType | (string|nil) The button layout type: "OK", "OKCancel", "YesNo", or "Continue". If nil, defaults to "OK" |
| WrapperModule MoveAxisIntoSoftLimitZone | ( | AxisID | , |
| margin | , | ||
| inst | ) |
Move the specified axis into the soft limit zone if it is currently outside.
Reads the soft limit enable state, max limit, min limit, and current machine position for the given axis. If the axis is already within limits or soft limits are disabled, returns immediately. Otherwise, determines whether the axis is closer to the min or max limit and computes a target position just inside the nearest limit (with an optional margin). Clamps the target to the valid range, then uses a Jogger to move the axis to the target position and waits for completion.
| AxisID | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| margin | (number|nil) Distance inside the soft limit boundary to target. Defaults to 0.01 if nil |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| name | ( | parameters | ) |
Format the error object's debug call stack as a human-readable multi-line string.
Iterates over self.DebugInfo (the stack frames captured at error creation time) and
| name | ( | s | ) |
Get the function name of the Lua caller at the specified stack level, skipping pcall frames.
Walks the Lua call stack starting at caller_level, building a slash-delimited list of function names. Stops when a named function is found (that is not pcall) or when the top of the stack is reached. Anonymous or unnamed frames are represented as "(unknown)". Returns both the composed name string and the final stack level used, so callers can use the level to retrieve additional debug info for the same frame.
| caller_level | (number|nil) The starting stack level to inspect. Defaults to 2 if not a number |
| name | ( | string | ) |
Call a Mach4 API function by name with automatic error handling (no metadata).
Convenience wrapper around w.api_e() that passes nil as the metadata argument, disabling support for allowable error codes. Accepts the API function name and its arguments as variadic parameters and delegates to WrapperModule.api_e(nil, ...).
| WrapperModule Jogger New | ( | axis | , |
| inst | ) |
Create a new Jogger instance for the specified axis.
Instantiates a new Jogger object using setmetatable and configures it with axis and instance information, jog mode (default: Continuous), and external jog parameters read from OEM parameters (ExternalJogAccel, ExternalContJogRate, ExternalJogIncremant). Also computes max_rate and min_rate for the axis. Raises an error if the axis ID is invalid or if the axis is not enabled. Calls w.SetStopStatus() to prepare for w.Sleep() usage.
| axis | (number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.Z_AXIS) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DbgCheckPoint new | ( | ) |
Create a new DbgCheckPoint instance with the specified name.
Initializes a new checkpoint object with an empty loci table and an empty recent table. The loci table stores checkpoint state entries keyed by id. The recent table tracks the recency of each id for ordered display.
| name | (string) A descriptive name for this checkpoint object (used in tostring() output) |
| WrapperModule Averager new | ( | num_points | ) |
Create a new Averager instance with the specified sample window size.
Instantiates a new Averager object using setmetatable. The points list starts empty. Once num_points samples have been added via sample(), older samples are discarded to maintain the sliding window. Both mean() and trend() operate on this window.
| num_points | (number) The maximum number of data points to retain in the sliding window |
| WrapperModule NewSerialConnection | ( | portnumber | , |
| setup | , | ||
| error_codes | ) |
Create and configure a new serial port connection wrapper.
Opens a serial port and configures it with the specified baud rate, data bits, stop bits, parity, and flow control settings. Returns a wrapper table with methods for reading, writing, and closing the port. Requires the luars232 Lua module to be available.
The returned wrapper table includes the following methods:
| portnumber | (number) The COM port number to open (e.g., 3 for COM3) |
| setup | (table|nil) Optional serial port configuration table with keys: |
| error_codes | (table|nil) Optional table of project-specific error codes attached to the wrapper |
| WrapperModule nice_decimal | ( | value | , |
| precision | , | ||
| width | ) |
Format a number as a readable decimal string, removing insignificant trailing zeros.
Formats the value using printf-style fixed-point notation with up to precision decimal places, then strips trailing zeros and a trailing decimal point. If width is specified, the result is left-padded with spaces on the right to honor the width while maintaining decimal alignment. If width is not specified, no padding is applied.
| value | (number) The numeric value to format |
| precision | (number|nil) Maximum number of decimal places to include. If nil, defaults to 4 |
| width | (number|nil) Total field width. If specified, result is padded with trailing spaces to this width |
| WrapperModule NPPEditor | ( | path_to_nppexe | ) |
Create a batch code generator function for opening a file in Notepad++.
Returns a closure that, when called with a file path, generates a batch command string to open that file in the specified Notepad++ executable using START (so that cmd does not block waiting for Notepad++ to exit).
| path_to_nppexe | (string) Full path to the Notepad++ executable |
| open_cmd | ( | url | ) |
Open a URL using the macOS 'open' command.
Open a URL in the default system browser or application.
Open a URL using the Linux xdg-open command.
Uses the macOS 'open' utility to open the specified URL or file path on Darwin/macOS systems. This command is cached after the first call. The result is determined by the exit code of os.execute().
| url | (string) The URL or file path to open |
Uses the xdg-open utility to open the specified URL or file path on X-based Linux distributions. This is the fallback open command used when neither Windows nor macOS is detected.
| url | (string) The URL or file path to open |
Detects the operating system and uses the appropriate method to open the given URL. On Windows, uses 'cmd /c START' via w.execute(). On macOS (Darwin), uses 'open'. On Linux, uses 'xdg-open'. The open command is cached after the first call for efficiency. If no suitable method can be determined, logs an error and returns false.
| url | (string) The URL or file path to open |
| WrapperModule OpenFileHelper | ( | ) |
Load and return the FileHelper module.
Uses require() to load the "FileHelper" Lua module and returns the module table. FileHelper provides INI file reading/writing, directory listing, and other file utilities used throughout the wrapper module.
| WrapperModule OpenURL | ( | url | ) |
Open a URL in the default system browser or application.
Detects the operating system and uses the appropriate method to open the given URL. On Windows, uses 'cmd /c START' via w.execute(). On macOS (Darwin), uses 'open'. On Linux, uses 'xdg-open'. The open command function is cached after the first call for efficiency. If no suitable method can be determined, logs an error and returns false.
| url | (string) The URL or file path to open |
| WrapperModule OperatorLog | ( | inst | , |
| log_msg | ) |
Log an operator action to bridgedb and set the Mach4 status message.
Logs the provided message to the DataInterface event log via d.LogEvent() with the "#operator" required tag if the message is non-empty (after stripping whitespace). Then sets the Mach4 last error message via mc.mcCntlSetLastError(). Non-string values are converted via tostring() before processing. If inst is not a number, falls back to w.GetSelectedInstance().
| inst | (number) The Mach4 instance handle. If not provided, uses the selected instance |
| log_msg | (string) The operator action message to log and display. Non-string values are converted via tostring() |
| WrapperModule PackagePath | ( | paths | , |
| update_cpath | ) |
| WrapperModule geom Parabola | ( | x0 | , |
| x1 | , | ||
| y_max | ) |
Return a function that calculates y-values for a parameter described by the specified geometry.
WrapperModule.geom.Parabola
This is a simplified version of the generic parabola.
| x0 | the starting point (x0,0) |
| x1 | the ending point (x1,0) |
| y_max | the peak/vertex of the parabola ((x0+x1)/2,y_max) |
| y_max | the peak/vertex of the parabola ((x0+x1)/2,y_max) |
| WrapperModule ParseAnalogSignalPath | ( | EncodedPath | , |
| default_instance | ) |
Parse an encoded analog input or output path string into a structured table.
Delegates to w.ParseIOSigPath() for the actual path parsing and caching. After parsing, insists that the resulting object is either an analog input signal or analog output signal; raises an error via w.Error() if it is not. Returns nil (without error) if the encoded path is empty or represents "(nothing selected)". The returned table includes the signal_id and type fields.
| EncodedPath | (string|nil) The encoded selection string from SignalSelector::GetEncodedSelection("$"). May be nil or empty to indicate no selection |
| default_instance | (number|nil) The default Mach4 instance to use if none is encoded in the path. If nil, uses the current instance |
| WrapperModule ParseCSVLine | ( | line | , |
| sep | ) |
Parse a single CSV line string into an array of field values.
Parses one line of CSV data, handling both quoted fields (which may contain the separator character) and unquoted fields. Quoted fields support escaped quotes by doubling them (""). The separator character defaults to comma if not specified. Returns both the array of parsed values and the count of fields found.
| line | (string) The CSV line string to parse |
| sep | (string|nil) The field separator character. If nil, defaults to ',' |
| WrapperModule ParseGCodeLine | ( | Line | , |
| Keywords | ) |
Parse a G-code line string and extract numeric values for specified keywords.
Searches the line for each keyword in the Keywords table (e.g., "X", "Y", "Z") and extracts the associated numeric value using the internal gnumber_pattern. Both uppercase and lowercase versions of each keyword are checked. Returns a table mapping each keyword to its numeric value, or nil for keywords not present on the line. Defaults to {"X", "Y", "Z", "F", "S"} if Keywords is not provided.
| Line | (string) The G-code line to parse |
| Keywords | (table|nil) An array of keyword strings to extract (e.g., {"X", "Y", "Z"}). If nil, defaults to standard axes plus F and S |
| WrapperModule parseINI | ( | name | ) |
Parse an INI-format file into a nested Lua table.
Reads the file at path 'name' and parses it as a Windows INI file. Sections are identified by lines matching [SectionName]. Key-value pairs are parsed from lines of the form key=value. Numeric values are converted to numbers; "true" and "false" strings are converted to booleans. Returns nil if the file cannot be opened.
| name | (string) Full path to the INI file to read |
References name().
| WrapperModule ParseIOSigPath | ( | path | , |
| default_instance | ) |
Parse an encoded I/O signal or register path string into a structured object table.
Parses an encoded selection string produced by SignalSelector::GetEncodedSelection("$") into a structured table describing the selected object. The path format is: [<instance>$]<type>$[<device>$]{<name>|<id>}
Supported types: OutputSignal, InputSignal, AnalogOutput, AnalogInput, IO, Register. Results are cached using a key combining the instance and path string. Returns nil (not an error) if the path is empty, nil, or "(nothing selected)".
| path | (string|nil) The encoded selection string from SignalSelector::GetEncodedSelection("$"). May be nil or empty |
| default_instance | (number|nil) The default Mach4 instance to use if none is encoded in the path. If nil, uses the current instance |
| WrapperModule parseISO8601Timestamp | ( | str | ) |
parse a timestamp formatted as an ISO8601 string.
WrapperModule.parseISO8601Timestamp
| ts_str | The ISO 8601 timestamp (https://en.wikipedia.org/wiki/ISO_8601) |
You can pass the (integer) result, like os.date("*t",result) to get a parsed timestamp, with year, month, day, etc.
| WrapperModule ParseMultipleReturnValuesFromFileQueueResponse | ( | value_from_user | ) |
Parse a comma-delimited key:value string from a file queue response into a structured table.
Splits the input string by commas and parses each token as a "key:value" pair. Recognized keys are: "ShowModalRC" (converted to boolean) and "value" (converted to number if possible). All other key:value pairs are stored in the additional_data sub-table, with values converted to numbers where possible. Leading and trailing whitespace is trimmed from both keys and values. Returns a result table with fields: show_modal_rc (boolean|nil), user_value (number|string|nil), and additional_data (table).
| value_from_user | (string|nil) A comma-delimited string of "key:value" pairs from a file queue response |
| WrapperModule ParseRegHandle | ( | path | ) |
Parse an I/O or register path string into its device and name components.
Splits a path string of the form "device/name" (or "device/sub/name") into the device portion and the trailing name portion by finding the last "/" separator. Returns the device string (everything before the last "/") and the name string (everything after the last "/").
| path | (string) The full path string to parse, e.g. "MachMotion/MyRegister" |
| WrapperModule ParseRegisterPath | ( | EncodedPath | , |
| default_instance | ) |
Parse an encoded register path string into a structured table.
Delegates to w.ParseIOSigPath() for the actual path parsing and caching. After parsing, insists that the resulting object is a register type; raises an error via w.Error() if it is not. Returns nil (without error) if the encoded path is empty or represents "(nothing selected)".
| EncodedPath | (string|nil) The encoded selection string from SignalSelector::GetEncodedSelection("$"). May be nil or empty to indicate no selection |
| default_instance | (number|nil) The default Mach4 instance to use if none is encoded in the path. If nil, uses the current instance |
| WrapperModule ParseStructuredGCodeComment | ( | comment_string | ) |
Parse a structured G-code comment string into comment text and an optional Lua data expression.
Parses a raw G-code comment (without surrounding parentheses) looking for a DATA: keyword. Everything before DATA: is treated as plain text comment. The portion after DATA: is evaluated as a Lua expression and the result stored in the returned table. The search for DATA: is case-insensitive. Parentheses in the input string are stripped before parsing. Returns a table with fields: comment (string), data (any), error (boolean), error_message (string).
| comment_string | (string) The raw G-code comment text to parse (without surrounding parentheses) |
| WrapperModule PasswordProtection | ( | level | ) |
Prompt the user to enter a password for the specified protection level, granting or denying access.
Checks if a password is configured for the requested level (1-3). If no password is configured, access is granted immediately. If a stay-logged-in session is active and within the timeout period, access is granted without prompting. Otherwise, displays a password entry dialog. Accepts the exact level password or any higher-level password. The master password "motion123" always grants access. Writes the authenticated level and timestamp to the profile on success.
| level | (number) The required access level to check (1, 2, or 3). Clamped to 1-3 range |
| WrapperModule pcall | ( | fn | , |
| ... ) |
Protected function call wrapper that ensures error objects include a full call stack.
Wraps xpcall() using w.ErrorHandler as the message handler, ensuring that any error raised (whether a string, number, or table) is converted to a rich error object created by w.Error() before being returned to the caller. This provides consistent, enriched error objects from all protected calls.
| WrapperModule PleaseWaitDialog | ( | WaitType | , |
| WaitMessage | , | ||
| WaitDataInvert | , | ||
| WaitData1 | , | ||
| WaitData2 | , | ||
| WaitData3 | ) |
Display a "Please Wait" modal dialog while waiting for a specified condition to be met.
Wraps _PleaseWaitDialog() in a w.pcall() protected call and enforces a single-instance guard via w.FuncTracing. Accepts either a WaitType table (preferred) or positional parameters. Displays a dialog with a pulsing progress bar and a cancel button while polling the condition. Supports all PleaseWaitType variants: MachState, Signal, IO, Register, FileLoading, TimeDelay, OEMParamSig, Function, DryRun, and TimeDelayOrCycleStartPressedFlag.
| WaitType | (table|number) A PleaseWaitType table (preferred) or a numeric PleaseWaitType constant |
| WaitMessage | (string|nil) Message to display in the dialog |
| WaitDataInvert | (boolean|nil) If true, inverts the condition check |
| WaitData1 | (any|nil) Primary wait data (signal handle, device name, mach state, etc.) |
| WaitData2 | (any|nil) Secondary wait data (register name, IO name, etc.) |
| WaitData3 | (any|nil) Tertiary wait data (expected value for register/IO comparisons) |
| WrapperModule __private zerobrane PopulateAPI | ( | object | , |
| namespace | , | ||
| id | ) |
Populate a ZeroBrane Studio API file with data from the specified object and namespace.
Wraps _PopulateAPI() in a protected call. If an error occurs during population, displays a message dialog with the error details. This function is safe to call at module load time without risk of crashing the screen chunk.
| object | (table) The table containing functions and values to expose in the API |
| namespace | (string) The dot-delimited namespace string corresponding to the object (e.g., "w", "m.screen") |
| id | (string) A unique identifier for this API population call, used to prevent duplicate generation |
| WrapperModule PostCommand | ( | command_name | , |
| as_opr_panel | , | ||
| wait_for_response | , | ||
| inst | ) |
Post a named user command to the file queue for execution.
Constructs a Lua code string that calls either w.RunUserCommandFromOperatorPanel() or w.RunUserCommand() depending on the as_opr_panel flag, then submits it via w.PostToFileQueue(). Use this to invoke commands from M-code or other non-screen contexts where direct execution is not appropriate.
| command_name | (string) The name of the user command to post for execution |
| as_opr_panel | (boolean|nil) If true, the command is posted as an operator panel command. If nil, defaults to false |
| wait_for_response | (boolean|nil) If true, waits for a reply from the file queue. If nil, defaults to false |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule PostToFileQueue | ( | command_string | , |
| wait_for_response | , | ||
| inst | ) |
Post a Lua command string to the file queue for asynchronous execution.
Creates a new LuaFileQueue via w.MakeNewFileQueue() and submits the command_string for execution. If wait_for_response is true, the queue entry will wait for a reply before completing. Returns the handle for the queued command, which can be passed to w.WaitForFileQueueResponse() to retrieve the result.
| command_string | (string) The Lua code string to execute via the file queue |
| wait_for_response | (boolean|nil) If true, the queue entry waits for a reply. If nil, defaults to false |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| math pow | ( | val | , |
| exponent | ) |
Raise a value to an integer or fractional exponent using the ^ operator.
@diagnostic disable-next-line: duplicate-set-field
Provides a math.pow() compatibility shim for Lua versions that do not include it. Equivalent to val ^ exponent.
| val | (number) The base value |
| exponent | (number) The exponent to raise val to |
| WrapperModule PretendCommandsAreFromOperatorPanels | ( | ) |
Determine whether screen commands should be treated as operator panel commands.
Checks the motion controller device name and the mm_NoTouchScreen OEM register to decide whether to pretend that commands originate from an operator panel. Returns true if the motion controller is a simulator (Sim0 or SimDev0) or if mm_NoTouchScreen is non-zero. Returns false if mm_NoTouchScreen is set to -1 (explicit override for testing real control behavior).
| WrapperModule FunctionQueue Print | ( | ) |
Log all registered functions in this FunctionQueue group to the Mach log.
Iterates through all registered functions and logs their index, name, and function reference using w.Log(). Also logs a header and footer indicating the group name and item count.
| WrapperModule PrintDebugMessage | ( | CustomMessage | , |
| OpenMessageDialog | , | ||
| FileName | , | ||
| LineNumber | ) |
Print a debug message to the Mach4 log and optionally show a dialog, when debugging is enabled.
If w.IsDebugging() returns true, resolves the caller's source file and line number from the Lua debug stack (falling back to FileName/LineNumber parameters if stack info is unavailable). Formats and sends the message via mc.mcCntlLog() and mc.mcCntlSetLastError(). If OpenMessageDialog is true, also displays the message in a wxMessageBox dialog. Does nothing if debugging is not enabled.
| CustomMessage | (string) The debug message to display and log. Non-string values are converted with tostring() |
| OpenMessageDialog | (boolean) If true, opens a wxMessageBox dialog in addition to logging |
| FileName | (string|nil) Override source file name for the log entry. If nil, resolved from debug stack |
| LineNumber | (number|nil) Override line number for the log entry. If nil, resolved from debug stack |
| WrapperModule ProcessActiveCommand | ( | command_name | , |
| command_table | ) |
Process a single active command's feedback state and update its target if the state changed.
Checks whether enough time has elapsed since the last feedback check by comparing os.clock() against command_table.FeedbackNextCheck. If the check interval has elapsed or this is the first check, evaluates the feedback state via w.GetCommandFeedbackState(). If the state has changed since LastState, calls w.SetCommandTargetState() to propagate the new state. Updates command_table.FeedbackNextCheck for the next scheduled check.
| command_name | (string) The name of the command being processed |
| command_table | (table) The command configuration table containing FeedbackCheckPeriod, FeedbackNextCheck, and LastState fields |
| WrapperModule ProcessActiveCommandFeedback | ( | feedback_name | ) |
Process the feedback state for a single named feedback and update its associated I/O output.
Evaluates the feedback function for the given feedback_name by checking user.UserCommandsFeedback first, then m.CommandFeedbacks. If the state has changed since the last check (m.CurrentActiveFeedbacks[feedback_name].LastState), updates the associated I/O point in the Commands device (creating it if needed) and records the new state.
| feedback_name | (string) The name of the command feedback to process |
| WrapperModule ProcessActiveCommands | ( | ) |
Process all active commands and feedbacks, refreshing their states each screen update.
Checks if the active command and feedback lists need reloading (m.RELOAD_ACTIVE_COMMANDS flag or nil tables). Iterates over m.CurrentActiveCommands and calls w.ProcessActiveCommand() for each entry with Value > 0. Iterates over m.CurrentActiveFeedbacks and calls w.ProcessActiveCommandFeedback() for each entry with Value > 0. Logs errors if either table is nil after loading.
| WrapperModule Protected | ( | ... | ) |
Execute a function with protected call handling, showing full debug error dialogs on failure.
Wraps w.ProtectedChk() with nil checkpoint and nil clean_message, which means errors always produce a full debug wxMessageBox with error message, debug info, function name, and parameters. Use this during development or in contexts where the full stack trace is always desired.
| ... | (any) The function to call followed by its arguments (same signature as pcall) |
| WrapperModule ProtectedChk | ( | chk | , |
| clean_message | , | ||
| ... ) |
Execute a function with protected call handling, showing error dialogs on failure.
Wraps a function call in w.pcall() and handles any errors that occur. On error, formats a detailed message including the error, debug info, called function name, parameters, and optional checkpoint context. If clean_message is true, shows a simple GMS warning dialog instead of a full wxMessageBox. If clean_message is false (default), shows the full debug message in a wxMessageBox. Returns all return values from the protected call on success, or nothing on failure.
| chk | (table|nil) An optional DbgCheckPoint object for additional context. If nil, no checkpoint info is shown |
| clean_message | (boolean|nil) If true, show a simple GMS dialog instead of a full debug message box. If nil, defaults to false |
| ... | (any) The function to call followed by its arguments (same signature as pcall) |
| WrapperModule ProtectedMsg | ( | ... | ) |
Execute a function with protected call handling, showing simplified error dialogs when not debugging.
Wraps w.ProtectedChk() with context-sensitive error reporting. When debugging mode is active (w.IsDebugging() returns true), shows the full debug error message via wxMessageBox. When not debugging, shows a clean, user-friendly GMS warning dialog without the full call stack.
| ... | (any) The function to call followed by its arguments (same signature as pcall) |
| wrapper read | ( | self | , |
| read_len | , | ||
| timeout | ) |
Read data from the serial port.
Public wrapper around _read() that provides protected call handling. If an error occurs during the read, it is caught and raised via w.Error(). The underlying _read() function opens the port, reads up to read_len bytes, and logs the elapsed time and data received.
| read_len | (number) The number of bytes to attempt to read |
| timeout | (number|nil) Timeout in milliseconds. If nil, defaults to 5000ms |
| WrapperModule ReadCSV | ( | FileName | , |
| options | ) |
| WrapperModule ReadCSVIntoTableByHeader | ( | filename | , |
| options | ) |
| WrapperModule ReadGcodeHeaderParameters | ( | gcode_file | ) |
Parse structured key-value parameter blocks from a G-code file header.
Reads lines from a G-code file (or the currently loaded G-code if gcode_file is nil) looking for a block delimited by "(Start Parameters)" and "(End Parameters)" comments. Within this block, parses G-code comments of the form: (TopLevelKey: key1: value1, key2: value2, ...) or (key1: value1, key2: value2, ...) and builds a nested table of the extracted key-value pairs. Lines that do not match the structured format are ignored. Handles both file-based and Mach-resident G-code.
| gcode_file | (string|nil) Full path to the G-code file to parse. If nil, reads from the currently loaded G-code in Mach |
| WrapperModule ReadListHistory | ( | filename | ) |
Read a list history file and return its contents as an array of strings.
Opens the specified file and reads each line, unescaping \n sequences back to newlines. Skips consecutive duplicate lines. Returns an empty table if the file does not exist or cannot be opened.
| filename | (string) Full path to the history file to read |
| WrapperModule ReadTableRegister | ( | inst | ) |
Read and clear the raw table string from the shared table register.
Reads the current string value from the SendTableAcrossRegister OEM register, then clears the register by writing an empty string. Returns the raw serialized table string.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReadTextFile | ( | FileName | ) |
Read the entire contents of a text file into a string.
Opens the file in read mode and reads all content using file:read("*all"). Returns nil and an error message if the file cannot be opened.
| FileName | (string) Full path to the text file to read |
| WrapperModule ReadUserCommandFile | ( | filepath | ) |
Read and parse a user command INI file into a table of command configuration tables.
Opens the INI file at filepath using FileHelper's IniReader and reads all data. Parses dot-delimited keys (section.key = value) into a nested table structure where each section becomes a command configuration sub-table. Keys without a dot separator are ignored.
| filepath | (string) Full path to the user command INI file to read |
| WrapperModule ReceiveTableAcrossRegister | ( | inst | ) |
Read and deserialize a Lua table from the table register if one is available.
Checks whether a table is currently stored in the register via IsTableInRegister(). If present, reads the raw string via ReadTableRegister() and deserializes it using EvaluateLuaExpression(). Returns an error if no table is available.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReceiveTableAcrossRegisterWait | ( | inst | ) |
Wait for a Lua table to appear in the table register, then read and return it.
Blocks execution by polling IsTableInRegister() with w.Sleep(10) until a table is present. Once found, reads the raw string from the register via ReadTableRegister(), evaluates it as a Lua expression via EvaluateLuaExpression(), and returns the deserialized table data.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| Recursive | ( | t | ) |
Recursively write a condition set and all nested sub-sets to the GMS command string.
This is a local recursive closure defined inside WrapperModule.CreateSystemGlobalMessage(). It delegates directly to WriteConditionSet() which validates the set table, serializes each condition entry (IO, Signal, OEMSignal, Pound, State, Axis, Register) as pipe-delimited tokens, and recursively processes nested Sets entries. Returns the serialized condition set string including StartSet, condition tokens, nested set strings, and EndSet markers.
| t | (table) A condition set table with keys: 'Set' (number 0-2), 'Conditions' (table), and optionally 'Sets' (table of nested condition sets) |
| WrapperModule RegenerateToolPathDialog | ( | non_modal | , |
| inst | ) |
Display a modal or non-modal tool path regeneration progress dialog.
Validates that the machine is in IDLE state and a G-code file is loaded before proceeding. Optionally calls m.StopSpindleDuringToolPathRegen() if defined. Creates a wx dialog with a progress gauge and percentage label, starts mc.mcToolPathGenerate(), and polls progress via a wx.wxTimer firing every 50ms. The dialog can be cancelled via a Cancel button which calls mc.mcToolPathGenerateAbort(). On completion or cancellation, rewinds the G-code file and runs "PostRegenerateToolPath" hooks if m.RunHooks is defined.
| non_modal | (boolean|nil) If true, shows the dialog as non-modal. If nil, defaults to false (modal) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule FunctionQueue Register | ( | func | ) |
Register a named function in this FunctionQueue group.
Adds a function to the queue's function list under the given name. If only a function is provided (no name), the function attempts to auto-discover the name by searching common module tables (m, m.screen, w, user). Non-function values are rejected with a log message.
| name | (string|function) The name to register the function under, or the function itself (name will be auto-discovered) |
| func | (function|nil) The function to register. If name is a function, this parameter is unused |
References func().
| WrapperModule RegSendCommand | ( | Device | , |
| RegName | , | ||
| command | , | ||
| inst | ) |
Send a command string to a register and return the response.
Gets the register handle for Device/RegName via w.GetRegHandle(), then sends the command string via mc.mcRegSendCommand(). Returns an error if any of the instance, device name, register name, or command are not strings, if the register handle cannot be obtained, or if the API call returns a non-zero error code.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the command register to send the command to |
| command | (string) The command string to send to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReleaseCycleStartHold | ( | reason | ) |
Release the active Cycle Start Hold and log the release reason.
Writes the given reason string to the mm_CycleStartModeReleaseReason register, writes 0 to the mm_CycleStartMode register to deactivate the hold, and logs the release action with the provided reason. If reason is nil, "Unknown" is used.
| reason | (string|nil) A description of why the hold is being released. Defaults to "Unknown" if nil |
| WrapperModule ReleasedForCycleStart | ( | ) |
Check whether the most recent Cycle Start Hold release was triggered by Cycle Start.
Reads the mm_CycleStartModeReleaseReason register string and returns true if the reason is exactly "Cycle Start". This allows callers to distinguish between a Cycle Start release and other release reasons (e.g., abort, error).
| WrapperModule ReleaseInhibitJogOnAllAxes | ( | release_all | , |
| inst | ) |
Release the jog inhibit on all axes (mc.AXIS0 through mc.MC_MAX_AXES-1).
Iterates through all axis IDs from mc.AXIS0 to mc.MC_MAX_AXES-1 and calls ReleaseInhibitJogOnAxis() for each, passing the release_all flag. If release_all is true, all inhibit counters are forced to zero. Otherwise each counter is decremented by 1.
| release_all | (boolean|nil) If true, forces all inhibit counters to 0 |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReleaseInhibitJogOnAxis | ( | axis | , |
| release_all | , | ||
| inst | ) |
Decrement the jog inhibit counter for a specific axis, enabling jogging when it reaches zero.
Reads the InhibitJogAxis{axis} register from the MachMotion device. If release_all is true, sets the value to 0 unconditionally. Otherwise, decrements the counter by 1, clamped to a minimum of 0. Writes the updated value back via SetRegValueLong(). Returns immediately without action if the axis is out of the valid range.
| axis | (number) The axis ID to release inhibit on (mc.AXIS0 through mc.MC_MAX_AXES-1) |
| release_all | (boolean|nil) If true, forces the inhibit counter to 0 regardless of its current value |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReleaseInhibitJogOnCoordinatedAxes | ( | inst | ) |
Release the jog inhibit on all coordinated axes (mc.X_AXIS through mc.C_AXIS).
Iterates through axis IDs mc.X_AXIS through mc.C_AXIS and calls ReleaseInhibitJogOnAxis() for each, decrementing each axis's jog inhibit counter by 1.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ReleaseMCodeHold | ( | ) |
Decrement the MCode hold counter, releasing one hold request.
Delegates to DecrementMCodeHoldCount() to reduce the global MCode hold counter by one. When the counter reaches zero, the MCode hold becomes inactive.
| WrapperModule RemoveActiveDialog | ( | dlg_name | ) |
Remove a dialog from the active dialogs registry.
Sets the entry for the specified dialog name in the ActiveDlgs table to nil, effectively unregistering it from the active dialogs tracking system.
| dlg_name | (string) The name key of the dialog to remove from the registry |
| WrapperModule RemoveIO | ( | dev_name | , |
| io_name | ) |
Remove the permanent registration of a dynamically-created I/O point.
Sends a 'RemoveIO' command to the MachMotion plugin via the mm_LuaRequest register, which removes the I/O point from the profile so it will not be recreated on the next Mach4 startup. Note: The I/O point is NOT unregistered from the running system by this call - it only prevents recreation on startup. If dev_name is nil, defaults to 'MachMotion' as the device.
| dev_name | (string|nil) The device under which the I/O is registered. If nil, uses 'MachMotion' |
| io_name | (string) The name of the I/O point to remove from the profile |
| WrapperModule RemoveRegister | ( | dev_name | , |
| reg_name | ) |
Remove the permanent registration of a dynamically-created register.
Sends a 'RemoveRegister' command to the MachMotion plugin via the mm_LuaRequest register, which removes the register from the profile so it will not be recreated on the next Mach4 startup. Note: The register is NOT unregistered from the running system - it only prevents recreation on startup. If dev_name is nil, defaults to 'MachMotion' as the device.
| dev_name | (string|nil) The device under which the register is registered. If nil, uses 'MachMotion' |
| reg_name | (string) The name of the register to remove from the profile |
| WrapperModule table repr | ( | tbl | ) |
Produce a compact, single-line Lua-parsable string representation of a table.
Recursively formats a table as a compact string using val_to_str() for values and key_to_str() for non-array keys. Array elements are formatted first in order, then remaining key-value pairs are appended. All elements are joined by commas and wrapped in braces. Returns "nil" if tbl is nil.
| tbl | (table|nil) The table to format. Returns "nil" if tbl is nil |
| WrapperModule table pretty repr | ( | tbl | , |
| indent | , | ||
| has_key | ) |
Produce a human-readable, indented Lua-parsable representation of a table.
Recursively formats a table as a multi-line string with proper indentation. Array elements are formatted first (in order), then non-array key-value pairs are sorted by key and appended. Each nested table is indented by two additional spaces relative to its parent. The has_key flag suppresses leading indentation when a table is itself the value of a key (to avoid double-indenting).
| tbl | (table|nil) The table to format. Returns "nil" if tbl is nil |
| indent | (string|nil) The current indentation string. Defaults to "" if nil |
| has_key | (boolean|nil) If true, suppresses leading indentation on the opening brace. Defaults to false |
| wrapper request | ( | self | , |
| request_cmd | , | ||
| read_len | , | ||
| timeout | ) |
Write a command string and read back a response.
Combines write() and read() into a single request/response operation. Writes the command string to the serial port then immediately reads back the specified number of bytes.
| request_cmd | (string) The command string to write to the serial port |
| read_len | (number) The number of bytes to read in the response |
| timeout | (number|nil) Timeout in milliseconds for the read operation. If nil, uses default |
| wrapper requestBcc | ( | self | , |
| request_cmd | , | ||
| read_len | , | ||
| timeout | ) |
Write a BCC-checksummed command and read back a response.
Combines writeBcc() and read() into a single request/response operation. The command string is checksummed before being written to the serial port, then a read is performed to retrieve the response.
| request_cmd | (string) The command string to write (will be BCC-checksummed before sending) |
| read_len | (number) The number of bytes to read in the response |
| timeout | (number|nil) Timeout in milliseconds for the read operation. If nil, uses default |
| WrapperModule RequestCycleStartHold | ( | ) |
Request a Cycle Start Hold if one is not already active.
Checks whether a Cycle Start Hold is currently active via IsCycleStartHoldActive(). If a hold is already active, returns false without making any change. If no hold is active, writes 1 to the mm_CycleStartMode register to activate the hold and returns true.
| WrapperModule RequestData | ( | StructType | , |
| inst | ) |
Request structured data from the MachMotion plugin via a command register.
Sends a command string (StructType) to the "mm_LuaRequest" register in the MachMotion device via w.RegSendCommand(). If the plugin responds with a non-nil string, the response is evaluated as a Lua expression via load() and returned as a table. Returns an error if the plugin does not respond, if the response is nil, or if the response is not valid Lua.
| StructType | (string) The request type string to send to the MachMotion plugin |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance (note: internally overrides to current instance) |
| WrapperModule RequestMCodeHold | ( | ) |
Increment the MCode hold counter, requesting a hold.
Delegates to IncrementMCodeHoldCount() to increase the global MCode hold counter by one. Multiple callers can independently request a hold; the hold remains active until all requests are released via ReleaseMCodeHold().
| WrapperModule RequireParameterExist | ( | param | , |
| inst | ) |
Log a warning if the specified Mach4 control parameter does not exist.
Calls w.DoesParameterExist() to check whether the given parameter number is defined in the current Mach4 instance. If it does not exist, logs a formatted warning message via w.Log(). Does not raise an error.
| param | (number) The Mach4 control parameter number to verify |
| inst | (number|nil) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ResetCycleStartPressedFlag | ( | ) |
Clear the Cycle Start Pressed Flag and mark it as inactive.
Writes 0 to the CycleStartPressedFlag OEM parameter and sets the internal CycleStartPressedFlag.Active field to false. Logs a message if the flag was previously active.
| WrapperModule ResetGCodeCNTL1MST | ( | inst | ) |
Clear the G-code CNTL1 MST bit to re-enable M/S/T waits.
Reads the SV_CNTL1 pound variable, clears bit 1 (the MST suppression flag) via SetValueBit() if it is currently set, and writes the updated value back via mc.mcCntlSetPoundVar(). When this bit is clear, Mach4 will wait for M, S, and T codes to complete before proceeding.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule RestoreInstance | ( | inst | ) |
Restore the active Mach4 instance to the stored or specified instance.
If inst is nil or out of range [0, MC_MAX_CONTROLLERS - 1], restores MINSTANCE to the value previously saved in WrapperModule.STORED_INST. Otherwise sets MINSTANCE to the provided inst value. Calls w.FunctionCompleted() with the restored instance on completion.
| inst | (number|nil) The instance to restore to, or nil to restore the previously stored instance |
| WrapperModule _TemporaryMachineState Revert | ( | ) |
Revert the machine state to the saved state and return any passed values.
Calls mc.mcCntlMachineStatePop() to restore the machine state that was saved when this TemporaryMachineState object was created. Designed to be wrapped around any return statement so the machine state is always restored, even when a function has multiple return points. Returns all arguments passed to it (except self), allowing it to be used inline in return statements.
| ... | (any) Values to pass through and return after reverting machine state |
| WrapperModule RotateAroundPoint | ( | x | , |
| y | , | ||
| angle | , | ||
| x_center | , | ||
| y_center | ) |
Rotate a point (x, y) by the specified angle around a center point.
Applies standard 2D rotation mathematics to rotate the given point counter-clockwise by the specified angle around (x_center, y_center). Designed for use with G68 coordinate system transformation. If angle, x_center, or y_center are not provided, retrieves them from the Mach4 system variables (mc.SV_ROTATION, mc.SV_ROTATION_X, mc.SV_ROTATION_Y).
| x | (number) X coordinate of the point to rotate |
| y | (number) Y coordinate of the point to rotate |
| angle | (number|nil) Rotation angle in degrees (CCW positive). If nil, reads from mc.SV_ROTATION |
| x_center | (number|nil) X coordinate of the rotation center. If nil, reads from mc.SV_ROTATION_X |
| y_center | (number|nil) Y coordinate of the rotation center. If nil, reads from mc.SV_ROTATION_Y |
| WrapperModule Round | ( | num | , |
| idp | , | ||
| nearestupdown | ) |
Round a number to a specified number of decimal places, with directional control.
-------------------— Rounding Wrapper -----------------------------------------------------—
Uses a multiplier of 10^idp to shift the decimal point, applies the selected rounding method, then shifts back. Supports round-down (floor), round-up (ceil), and round-to-nearest (default, 0.5 rounds up).
| num | (number) The number to round |
| idp | (number|nil) Number of decimal places to round to. If nil, defaults to 0 (round to integer) |
| nearestupdown | (number|nil) Rounding direction: -1 to round down, 1 to round up, any other value (or nil) to round to nearest |
| WrapperModule RunBatchCode | ( | batch_code_to_run | , |
| description | , | ||
| verbosity | ) |
Write and execute batch code in a temporary CMD script file.
Creates a temporary .cmd script file in TEMP%, writes the provided batch code into it (with an optional REM comment header), executes it via winapi.execute(), logs and raises an error if the exit code is non-zero, and removes the temporary file when done. Verbosity level controls whether the script content and output are logged.
| batch_code_to_run | (string) The batch file code to write and execute |
| description | (string|nil) Optional description written as a REM comment at the top of the script. Defaults to '' |
| verbosity | (number|nil) Logging verbosity level. If > 0, logs the script content and output. Defaults to 0 |
| WrapperModule RunLuaString | ( | expr_string | ) |
Run an arbitrary sized chunk of Lua code.
WrapperModule.RunLuaString
This function evaluates and runs an arbitrary-sized snippet of Lua. It does not assume that it returns anything. If you want to return something, include a return <stuff> at the end of the code snippet.
Examples – multiline code w.RunLuaString("w.wxMessageBox('Warning!')\ndanger=false\nw.wxMessageBox('The danger has passed!')") – Explicitly include a return to return a result (via <retval>.data) local area = (w.RunLuaString("return 2 * 2 * 3.1415926")).data – call a Mach API w.RunLuaString("w.api('mcCntlLog',inst,'I pity the fool who writes log messages this way!','MrT.mcs',5)")
Tests: Plugins/MachMotion/UnitTests/Tests/WrapperModule/t_runlua.mcs
| WrapperModule RunUserCommand | ( | command_name | , |
| from_opr_panel | ) |
Execute a named user command, optionally treating it as coming from an operator panel.
Looks up the command by name via w.CreateFunctionFromCommand() and executes it using w.pcall(). If from_opr_panel is false, checks w.PretendCommandsAreFromOperatorPanels() to determine whether to elevate the command to operator panel status. Logs the command name, the resolved function, and any custom action parameter. Logs errors if the command execution fails.
| command_name | (string) The name of the user command to execute |
| from_opr_panel | (boolean|nil) If true, the command is treated as originating from an operator panel. If nil, defaults to false |
| WrapperModule RunUserCommandFromOperatorPanel | ( | command_name | ) |
Execute a named user command as if it originated from an operator panel.
Convenience wrapper that calls w.RunUserCommand(command_name, true), always passing true for the from_opr_panel flag. This bypasses screen-level safety checks that would otherwise require a cycle start confirmation.
| command_name | (string) The name of the user command to execute as an operator panel command |
| WrapperModule Averager sample | ( | value_op | ) |
Add a sampled value to the window and return a summary statistic.
Inserts the new value at the front of the points list and removes old values beyond num_points to maintain the sliding window. If value_op is nil, returns the arithmetic mean. If value_op is 'noop', returns nothing. Otherwise, calls the named method on the Averager object (e.g., 'trend', 'mean', 'variance').
| value | (number) The new sample value to add to the window |
| value_op | (string|nil) The summary operation to perform: nil or 'mean' for average, 'noop' to skip summary, or any other Averager method name (e.g., 'trend') |
| WrapperModule saveINI | ( | name | , |
| t | ) |
Save a nested table as an INI-format file.
Writes the table 't' to the file at path 'name' in Windows INI format. The table is expected to be a two-level structure where the outer keys are section names and the inner keys are key-value pairs. Each section is written as [section] followed by key=value lines. The file is overwritten if it already exists.
| name | (string) Full path to the INI file to write |
| t | (table) Two-level table where t[section][key] = value |
References name().
| WrapperModule SaveUserCommand | ( | command_table | ) |
Save a command configuration table to its INI file in the UserCommands folder.
Opens the INI file for the command (determined by command_table.Name via w.GetUserCommandFilename()) and writes each key-value pair from command_table as a string entry under the section named command_table.Name. Uses the FileHelper INI writer.
| command_table | (table) The command configuration table to save. Must include a 'Name' field |
| WrapperModule Scale | ( | Input | , |
| InputMIN | , | ||
| InputMAX | , | ||
| OutputMIN | , | ||
| OutputMAX | ) |
Scale an input value from one numeric range to another.
------------------—END GCode Formatting Wrapper--------------------------— -------------------— Scale Wrapper -------------------—
Applies a linear mapping: Output = ((Input - InputMIN) / (InputMAX - InputMIN)) * (OutputMAX - OutputMIN) + OutputMIN. All parameters must be numbers; returns an error if any are not.
| Input | (number) The value to scale |
| InputMIN | (number) The minimum value of the input range |
| InputMAX | (number) The maximum value of the input range |
| OutputMIN | (number) The minimum value of the output range |
| OutputMAX | (number) The maximum value of the output range |
| WrapperModule SendGMSCommand | ( | reg_name | , |
| command | ) |
Send a command to the GlobalMonitoringSystem plugin via a register command.
Provides decoupled communication with the GMS plugin. On the first call, checks whether the GMS register exists and caches the result in w.__gms_not_present. If GMS is not present, returns a failure response without error, and logs a one-time notice when logging is enabled. If GMS is present, delegates to w.RegSendCommand() using the "GlobalMonitoringSystem" device on instance 0.
| reg_name | (string) The name of the GMS command register to send the command to |
| command | (string) The command string to send to the GMS plugin |
| WrapperModule SendTableAcrossRegister | ( | luatable | , |
| inst | ) |
Serialize and write a Lua table into the shared table register.
First checks whether the register is already occupied via IsTableInRegister(). If not occupied, serializes the table using WrapperModule.table.repr() and writes the string to the SendTableAcrossRegister OEM register. Returns an error if the register is already in use.
| luatable | (table) The Lua table to serialize and store in the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SendZabbixData | ( | data | ) |
| WrapperModule SetAnalogOutput | ( | idx | , |
| val | , | ||
| inst | ) |
Set the value of an analog output channel.
-------------------— Analog Wrappers --------------------------—
Writes the specified value to the analog output at the given index via mc.mcAnalogOutputWrite(). Returns an error if the index or value parameters are not numbers.
| idx | (number) The analog output channel index to write |
| val | (number) The value to write to the analog output |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetCache | ( | category | , |
| entry_name | , | ||
| value | ) |
Store a value in a named cache category entry.
Ensures the cache category exists via w.VerifyCacheExists(), assigns the provided value to cat[entry_name], and returns the value. Used by other cache-aware functions to persist computed or retrieved results for fast subsequent access.
| category | (string) The cache category to store the value in |
| entry_name | (string) The entry key to assign within the category |
| value | (any) The value to store in the cache |
| WrapperModule SetCommandButtonColors | ( | cmd_name | , |
| off_color | , | ||
| on_color | ) |
Set the on and off background colors for a command's button.
Updates the BgOffColor and BgOnColor fields of the command entry in m.Commands. Has no effect if m.Commands is nil or the command does not exist.
| cmd_name | (string) The name of the command whose button colors are to be set |
| off_color | (string) The background color when the command feedback state is off (e.g., "#FFFFFF") |
| on_color | (string) The background color when the command feedback state is on (e.g., "#00FF00") |
| WrapperModule SetCommandButtonLabels | ( | cmd_name | , |
| off_label | , | ||
| on_label | ) |
Set the on and off button label text for a command.
Updates the OffButtonLabel and OnButtonLabel fields of the command entry in m.Commands. If on_label is nil, both on and off labels are set to off_label. Has no effect if m.Commands is nil or the command does not exist.
| cmd_name | (string) The name of the command whose button labels are to be set |
| off_label | (string) The button label text when the command feedback state is off |
| on_label | (string|nil) The button label text when the command feedback state is on. If nil, uses off_label for both states |
| WrapperModule SetCommandButtonTextColors | ( | cmd_name | , |
| off_color | , | ||
| on_color | ) |
Set the on and off text colors for a command's button.
Updates the TxtOffColor and TxtOnColor fields of the command entry in m.Commands. Has no effect if m.Commands is nil or the command does not exist.
| cmd_name | (string) The name of the command whose button text colors are to be set |
| off_color | (string) The text color when the command feedback state is off (e.g., "#000000") |
| on_color | (string) The text color when the command feedback state is on (e.g., "#888888") |
| WrapperModule SetCommandFeedbackPeriod | ( | cmd_name | , |
| period_sec | ) |
| WrapperModule SetCommandTargetState | ( | command_name | , |
| command_table | , | ||
| feedback_state | ) |
Update the feedback target signal or I/O state for a command and its associated I/O point.
Sets the state of the command's feedback target (Input Signal, Output Signal, I/O, or User Script) based on the feedback_state boolean. Also updates the command's associated I/O point in the Commands device, creating it if necessary. Finally, updates the LastState field of the command in m.CurrentActiveCommands to reflect the new state.
| command_name | (string) The name of the command whose target state is being updated |
| command_table | (table) The command configuration table containing FeedbackTargetType, FeedbackTarget, and related fields |
| feedback_state | (boolean) The new feedback state to apply (true = active/on, false = inactive/off) |
| WrapperModule SetCurrentTool | ( | ToolNumber | , |
| inst | ) |
Set the current tool number and update all relevant Mach4 state.
Validates the tool number against the maximum tool number. If a user.SetCurrentTool override exists, delegates to it. Otherwise, saves the current tool as the previous tool via SetPreviousTool(), updates the CurrentTool tool change status, and calls mc.mcToolSetCurrent(). In Lathe mode, also sets the SV_CUR_LENGTH_INDEX pound variable and resolves the tool pocket. Writes the tool number to the CurrentTool OEM register on success.
| ToolNumber | (number) The tool number to set as current (must be in range [0, MaxTool]) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetCurrentToolPocket | ( | pocket_number | , |
| spindle | , | ||
| inst | ) |
Set and persist the current tool pocket number.
Validates the pocket number against the maximum number of tool pockets. Delegates to user.SetCurrentToolPocket() if a user override exists. Otherwise, determines the memory source from the ToolChangerMemorySource OEM parameter. For PLC memory source (or Random Memory ATC), validates the range. For Mach memory source, saves the current pocket as the previous pocket via SetPreviousToolPocket(), then writes the new pocket via SetToolChangeStatus(). In Lathe mode, also updates the Mach tool current via mc.mcToolSetCurrent(). Updates the CurrentToolPocket OEM register string on success.
| pocket_number | (number) The pocket number to set as current (must be in range [0, MaxPockets]) |
| spindle | (number|nil) The spindle number. Defaults to 1 if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetCustomCntlDwellBarValue | ( | value | ) |
Set the current value of the custom CNC dwell bar.
Formats the value to one decimal place and writes it to the CustomCntlDwellBar OEM parameter string. Typically called during a dwell operation to update progress.
| value | (number) The dwell bar value to set, formatted to one decimal place |
| WrapperModule SetCycleStartPressedFlag | ( | ) |
Set the Cycle Start Pressed Flag and record the activation time.
Writes 1 to the CycleStartPressedFlag OEM parameter, records the current time via os.clock(), and sets the internal CycleStartPressedFlag.Active field to true. The flag will be automatically reset by UpdateCycleStartPressedFlag() after OnTime milliseconds.
| WrapperModule SetDriveEnable | ( | val | , |
| inst | ) |
Set the drive enable signal state for the specified Mach4 instance.
Checks whether the "DriveEnable" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, sets it to the given value via w.SetOEMParamSig() and returns an error if the operation fails. Does nothing if the signal is not mapped.
| val | (boolean) The desired drive enable state: true to enable, false to disable |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetDriveEnableAll | ( | val | ) |
Set the drive enable signal state for all Mach4 instances.
Iterates over all Mach4 instances (0 to w.GetInstanceCount() - 1) and sets the "DriveEnable" OEM parameter signal for each instance that has it mapped, via w.SetOEMParamSig(). Returns an error immediately if any instance's signal set operation fails.
| val | (boolean) The desired drive enable state: true to enable, false to disable |
| WrapperModule Jogger SetFeedrate | ( | ) |
Set the commanded feedrate for this Jogger instance.
Updates the internal cmd_feedrate value and clamps it to the configured min_rate and max_rate limits. If feedrate is nil or not greater than zero, the existing cmd_feedrate is used but still clamped to the configured limits.
| feedrate | (number|nil) The desired feedrate in units/minute. If nil or <= 0, uses existing cmd_feedrate |
| WrapperModule SetFixtureSetterAutoName | ( | name | , |
| inst | ) |
Set the auto fixture setter selection by name and persist the change to the profile.
Retrieves all configured auto tool setters via w.GetAllAutoToolSetters(), validates that the given name exists in the list, then writes the name to the AutoSetterFixtureSelection OEM register string via w.SetOEMRegValueString(). Raises an error if the name is not found.
| name | (string) The name of the auto fixture setter to select |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule SetFixtureSetterManualName | ( | name | , |
| inst | ) |
Set the manual fixture setter selection by name and persist the change to the profile.
Retrieves all configured manual tool setters via WrapperModule.GetAllManualToolSetters(), validates that the given name exists in the list, then writes the name to the ManualSetterFixtureSelection OEM parameter string via w.eSetOEMParamValueString(). Raises an error if the name is not found in the configured setters.
| name | (string) The name of the manual fixture setter to select |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule SetGCodeCNTL1MST | ( | inst | ) |
Set the G-code CNTL1 MST bit to suppress M/S/T waits.
Reads the SV_CNTL1 pound variable, sets bit 1 (the MST suppression flag) via SetValueBit() if it is not already set, and writes the updated value back via mc.mcCntlSetPoundVar(). When this bit is set, Mach4 suppresses waits for M, S, and T codes.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetHardwareEnable | ( | val | , |
| inst | ) |
Set the hardware enable signal state for the specified Mach4 instance.
Checks whether the "HardwareEnable" OEM parameter signal is mapped via w.IsOEMParamSigMapped(). If mapped, sets it to the given value via w.SetOEMParamSig() and returns an error if the operation fails. Does nothing if the signal is not mapped.
| val | (boolean) The desired hardware enable state: true to enable, false to disable |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetHardwareEnableAll | ( | val | ) |
Set the hardware enable signal state for all Mach4 instances.
Iterates over all Mach4 instances (0 to w.GetInstanceCount() - 1) and sets the "HardwareEnable" OEM parameter signal for each instance that has it mapped, via w.SetOEMParamSig(). Returns an error immediately if any instance's signal set operation fails.
| val | (boolean) The desired hardware enable state: true to enable, false to disable |
| WrapperModule SetInstance | ( | instance | ) |
Set the active Mach4 instance number.
Assigns the provided instance number to the global MINSTANCE variable. Clamps out-of-range values (less than 0 or greater than MC_MAX_CONTROLLERS - 1) to 0 before assigning.
| instance | (number) The Mach4 instance number to set as the active instance |
| WrapperModule SetInstanceToSelectedInstance | ( | ) |
Set the active Mach4 instance to the currently selected instance.
Retrieves the currently selected instance via w.GetSelectedInstance() and assigns it to MINSTANCE. Clamps out-of-range values to 0 before assigning.
| WrapperModule SetIoState | ( | Device | , |
| IoName | , | ||
| val | , | ||
| inst | ) |
Set the state of an I/O point by device and name.
Gets the I/O handle via w.GetIoHandle(), reads the current state via mc.mcIoGetState(), and only calls mc.mcIoSetState() if the new value differs from the current state. Returns an error if the device name or I/O name are not strings, if the value is not a number or boolean, or if the I/O handle cannot be obtained.
| Device | (string) The device name under which the I/O point is registered |
| IoName | (string) The name of the I/O point to set |
| val | (number|boolean) The desired state to set on the I/O point |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule Jogger SetJogModeABS | ( | ) |
Set this Jogger to ABS (absolute position) jog mode.
Sets the internal mode to 2 (ABS mode) if not already in that mode. In ABS mode, the axis is commanded to move to an absolute machine position.
| WrapperModule Jogger SetJogModeContinuous | ( | ) |
Set this Jogger to continuous jog mode.
Sets the internal mode to 0 (Continuous mode) if not already in that mode. In continuous mode, the axis jogs at a continuous velocity until stopped.
| WrapperModule Jogger SetJogModeFeedrate | ( | ) |
Set this Jogger to feedrate jog mode.
Sets the internal mode to 3 (Feedrate mode) if not already in that mode. In feedrate mode, the axis is jogged at a specified feedrate using velocity jogging.
| WrapperModule Jogger SetJogModeIncremental | ( | ) |
Set this Jogger to incremental jog mode.
Sets the internal mode to 1 (Incremental mode) if not already in that mode. In incremental mode, the axis moves by a fixed increment each time a jog is commanded.
| WrapperModule SetMachEnable | ( | value | ) |
Enable or disable the Mach4 software enable for all instances.
Iterates over all Mach4 instances (0 to w.GetInstanceCount() - 1) and calls mc.mcCntlEnable() on each. Raises an error via w.Error() using the formatted Mach error message if any instance's enable call fails. Calls w.FunctionCompleted() on success.
| value | (boolean) The desired enable state: true to enable, false to disable |
| WrapperModule SetMotorCountsPerUnitFromProfile | ( | MotorID | , |
| value | , | ||
| inst | ) |
Set the counts-per-unit value for a motor in the Mach4 profile.
Writes value to the CountsPerUnit key in the Motor{MotorID} profile section via mc.mcProfileWriteDouble(). Raises an error via w.Error() if the profile write fails.
| MotorID | (number) The motor ID whose counts-per-unit to set |
| value | (number) The counts-per-unit value to store |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetMotorMaxAccelFromProfile | ( | MotorID | , |
| value | , | ||
| inst | ) |
Set the maximum acceleration for a motor in the Mach4 profile.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then writes value * counts_per_unit to the MaxAccel key in the Motor{MotorID} profile section via mc.mcProfileWriteDouble(). Raises an error via w.Error() if the profile write fails.
| MotorID | (number) The motor ID whose maximum acceleration to set |
| value | (number) The maximum acceleration to store, in units per second squared (setup units) |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetMotorMaxVelocityFromProfile | ( | MotorID | , |
| value | , | ||
| inst | ) |
Set the maximum velocity for a motor in the Mach4 profile.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then writes value * counts_per_unit to the MaxVelocity key in the Motor{MotorID} profile section via mc.mcProfileWriteDouble(). Raises an error via w.Error() if the profile write fails.
| MotorID | (number) The motor ID whose maximum velocity to set |
| value | (number) The maximum velocity to store in setup units per minute |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetMotorSoftMaxLimitFromProfile | ( | MotorID | , |
| value | , | ||
| inst | ) |
Set the soft maximum limit for a motor in the Mach4 profile.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then writes value * counts_per_unit to the SoftMaxLimit key in the Motor{MotorID} profile section via mc.mcProfileWriteDouble(). Raises an error via w.Error() if the profile write fails.
| MotorID | (number) The motor ID whose soft maximum limit to set |
| value | (number) The soft maximum limit to store in setup units |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetMotorSoftMinLimitFromProfile | ( | MotorID | , |
| value | , | ||
| inst | ) |
Set the soft minimum limit for a motor in the Mach4 profile.
Reads the motor's counts-per-unit from the profile via GetMotorCountsPerUnitFromProfile(), then writes value * counts_per_unit to the SoftMinLimit key in the Motor{MotorID} profile section via mc.mcProfileWriteDouble(). Raises an error via w.Error() if the profile write fails.
| MotorID | (number) The motor ID whose soft minimum limit to set |
| value | (number) The soft minimum limit to store in setup units |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetNotificationBackgroundColour | ( | Identifier | , |
| rr | , | ||
| gg | , | ||
| bb | ) |
Set the background color of an existing GMS notification.
Sends a "SetNotificationBg" command to the GMS plugin via w.SendGMSCommand() with the identifier and RGB color values formatted as a pipe-delimited string. The identifier must be a valid positive numeric handle previously returned by w.CreateGMSNotification() or w.CreateGMSDialog().
| Identifier | (number) The GMS notification handle returned by w.CreateGMSNotification() or w.CreateGMSDialog() |
| rr | (number) Red component of the background color (0-255) |
| gg | (number) Green component of the background color (0-255) |
| bb | (number) Blue component of the background color (0-255) |
| WrapperModule SetOEMParamReg | ( | ParamName | , |
| Val | , | ||
| inst | ) |
Set the value of a register or analog output pointed to by an OEM parameter register object.
Retrieves the register object associated with ParamName via w.GetOEMParamRegObject(). If the object is an analog output signal, sets it via w.SetAnalogOutput(). If it is a register, sets it via w.SetRegValue(). Returns an error if the object cannot be retrieved or if the set operation fails.
| ParamName | (string) The OEM parameter name whose register object points to the target register or analog output |
| Val | (number) The value to write to the register or analog output |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMParamSig | ( | SigName | , |
| Val | , | ||
| inst | ) |
Set the state of a signal or I/O point referenced by an OEM parameter register.
Convenience wrapper that retrieves the OEM parameters device name via w.GetOEMParametersDevice() and delegates to w.SetParamSig() with that device.
| SigName | (string) The OEM parameter register name of the signal to set |
| Val | (boolean) The desired signal or I/O state to set |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMParamValue | ( | RegName | , |
| val | , | ||
| inst | ) |
Set the numeric value of an OEM parameter register.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), gets the register handle via w.GetRegHandle(), and sets the numeric value using mc.mcRegSetValue(). Returns an error if the instance, device, or register name is invalid, if the value is not a number, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM parameter register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMParamValueBit | ( | ParamName | , |
| BitIdx | , | ||
| state | , | ||
| inst | ) |
Set or clear a specific bit in an OEM parameter value.
Reads the current value of the OEM parameter identified by ParamName via w.GetOEMParamValue(), sets or clears the bit at the zero-indexed position BitIdx using w.SetValueBit(), and writes the result back via w.SetOEMParamValue(). The state parameter defaults to true if nil. Passes through any errors from the read or write operations.
| ParamName | (string) The name of the OEM parameter to modify |
| BitIdx | (number) The zero-indexed bit position to set or clear |
| state | (boolean|nil) The desired bit state - true to set, false to clear. If nil, defaults to true |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMParamValueBool | ( | RegName | , |
| value | , | ||
| inst | ) |
Set an OEM parameter value to a boolean (stored as 1 or 0).
Converts the boolean value to a numeric value (1 for true, 0 for false) and writes it to the OEM parameter register identified by RegName via w.SetOEMParamValue(). Returns an error if the value parameter is not a boolean type.
| RegName | (string) The name of the OEM parameter register to set |
| value | (boolean) The boolean value to write - true stores 1, false stores 0 |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMParamValueString | ( | RegName | , |
| val | , | ||
| inst | ) |
Set the string value of an OEM parameter register.
Retrieves the OEM parameters device name via w.GetOEMParametersDevice(), gets the register handle via w.GetRegHandle(), and sets the string value using mc.mcRegSetValueString(). Returns an error if the instance, device, register name, or value type is invalid, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM parameter register to set |
| val | (string) The string value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMRegValue | ( | RegName | , |
| val | , | ||
| inst | ) |
Set the numeric value of an OEM register.
Retrieves the OEM register device name via w.GetOEMRegisterDevice(), gets the register handle via w.GetRegHandle(), and sets the numeric value using mc.mcRegSetValue(). Returns an error if the instance, device, or register name is invalid, if the value is not a number, or if the register handle cannot be obtained.
| RegName | (string) The name of the OEM register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMRegValueBit | ( | RegName | , |
| BitIdx | , | ||
| state | , | ||
| inst | ) |
Set or clear a specific bit in an OEM register value.
Reads the current value of the OEM register identified by RegName via w.GetOEMRegValue(), sets or clears the bit at the zero-indexed position BitIdx using w.SetValueBit(), and writes the result back via w.SetOEMRegValue(). The state parameter defaults to true if nil. Passes through any errors from the read or write operations.
| RegName | (string) The name of the OEM register to modify |
| BitIdx | (number) The zero-indexed bit position to set or clear |
| state | (boolean|nil) The desired bit state - true to set, false to clear. If nil, defaults to true |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetOEMRegValueString | ( | RegName | , |
| val | , | ||
| inst | ) |
Set the value of a register to a string.
| RegName | The name of the register to set. |
| val | The string value to set the register to. |
| inst | The instance of the module (optional). |
This function sets the value of a register to a string. It first retrieves the device associated with the register, then gets the handle for the register. If the handle is valid, it sets the register's value to the provided string. If any step fails, it returns an error message.
| WrapperModule SetParameter | ( | param | , |
| value | , | ||
| inst | ) |
Set the value of a Mach4 control parameter and update the cache.
Verifies that the parameter exists via w.RequireParameterExist(), writes the new value via mc.mcCntlSetParameter() using the w.api() wrapper, and stores the result in the parameter cache via w.SetCache().
| param | (number) The Mach4 control parameter number to set |
| value | (number) The new value to write to the control parameter |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetParameterBit | ( | param | , |
| bit | , | ||
| value | , | ||
| inst | ) |
Set a specific bit of a Mach4 control parameter to a given state.
Reads the current parameter value via mc.mcCntlGetParameter(), sets the bit at the specified zero-indexed position to the given boolean state using w.SetValueBit(), writes the result back via mc.mcCntlSetParameter(), and updates the parameter cache. Verifies the parameter exists via w.RequireParameterExist() before reading.
| param | (number) The Mach4 control parameter number to modify |
| bit | (number) The zero-indexed bit position to set within the parameter value |
| value | (boolean|number) The desired bit state - truthy to set the bit, falsy to clear it |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetParamSig | ( | Device | , |
| SigName | , | ||
| Val | , | ||
| inst | ) |
Set the state of a signal or I/O point referenced by a parameter register.
Reads the current signal state via w.GetParamSig() first; if the state already matches Val, returns success immediately without writing. Otherwise retrieves the IOSig object via w.GetParamIOSigObject() and sets the appropriate signal or I/O state:
| Device | (string) The device name under which the parameter register is stored |
| SigName | (string) The register name of the parameter signal to set |
| Val | (boolean) The desired signal or I/O state to set |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetPreviousTool | ( | PreviousTool | , |
| inst | ) |
Store the previous tool number in the tool change status.
Writes PreviousTool to the tool change status via w.SetToolChangeStatus(). This is typically called before updating the current tool so that the previous tool can be recalled.
| PreviousTool | (number) The tool number to store as the previous tool |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetPreviousToolPocket | ( | pocket_number | , |
| spindle | , | ||
| inst | ) |
Store the previous tool pocket number in the tool change status.
Writes PreviousPocket to the tool change status via w.SetToolChangeStatus(). This is typically called before updating the current tool pocket so that the previous pocket can be recalled. If spindle is not a number, defaults to the currently selected spindle.
| pocket_number | (number) The pocket number to store as the previous pocket |
| spindle | (number|nil) The spindle number. Defaults to the selected spindle if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetProbeFeedbackPositions | ( | positionnumber | , |
| val | ) |
Store a probe feedback position value in the OEM parameter for a given position index.
Validates that positionnumber is a number in the range [0, 5], then writes val to the OEM parameter named "ProbeFeedbackPosition_{positionnumber}" via w.SetOEMParamValue(). Raises an error via w.Error() if positionnumber is out of range or if the write fails.
| positionnumber | (number) The position slot index to write to (0 through 5 inclusive) |
| val | (number) The position value to store in the OEM parameter |
| WrapperModule SetRegValue | ( | Device | , |
| RegName | , | ||
| val | , | ||
| inst | ) |
Set the numeric value of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and writes the value using mc.mcRegSetValue(). Returns an error if the device name or register name are not strings, if the value is not a number or boolean, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to set |
| val | (number) The numeric value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetRegValueLong | ( | Device | , |
| RegName | , | ||
| val | , | ||
| inst | ) |
Set the long integer value of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and writes the value using mc.mcRegSetValueLong(). Returns an error if the device name or register name are not strings, if the value is not a number or boolean, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to set |
| val | (number) The integer value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetRegValueString | ( | Device | , |
| RegName | , | ||
| val | , | ||
| inst | ) |
Set the string value of a register.
Gets the register handle for Device/RegName via w.GetRegHandle() and writes the string value using mc.mcRegSetValueString(). Returns an error if the device name, register name, or value are not strings, or if the register handle cannot be obtained.
| Device | (string) The device name under which the register is stored |
| RegName | (string) The name of the register to set |
| val | (string) The string value to write to the register |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetSelectedInstance | ( | inst | ) |
Set the selected Mach4 instance and notify listeners of the change.
Logs the caller function name via w.GetCurrFnName(), writes the new selected instance value to the "core/global/SelectedInstance" register via w.SetRegValue(), and raises an error via w.Error() if the write fails. Calls w.UpdateSelectedInstance() to refresh the cached selected instance. If m.CommonSelectedInstanceChanged is defined, calls it to notify listeners of the change. Calls w.FunctionCompleted() on success.
| inst | (number) The Mach4 instance number to set as the selected instance |
| WrapperModule SetSelectedSpindle | ( | spindle | , |
| inst | ) |
Set the selected spindle number and persist the change.
Delegates to user.SetSelectedSpindle() if a user override exists. Otherwise, validates the spindle number (defaulting to the currently selected spindle if not a number), then writes the value to the TC_SelectedSpindleNumber OEM parameter via w.eSetOEMParamValue(). Falls back to the default spindle if spindle is less than 1.
| spindle | (number) The spindle number to set as selected |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetSelectedTool | ( | ToolNumber | , |
| inst | ) |
Set the selected (staged) tool number for the next tool change.
If a user.SetSelectedTool override exists, delegates to it. Otherwise, in Mill mode writes the tool number to the SV_CUR_SELECTED_TOOL pound variable via mc.mcCntlSetPoundVar(). In Lathe mode, no action is taken beyond returning the tool number.
| ToolNumber | (number) The tool number to stage for the next tool change |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetSignalEnable | ( | Signal | , |
| Value | , | ||
| inst | ) |
Enable or disable a signal.
Gets the signal handle via w.GetSignalHandle(). If Value is false (disabling), first sets the signal state to 0 via mc.mcSignalSetState() before calling mc.mcSignalEnable(). Returns an error if the Signal parameter is not a number or if the enable call returns a non-zero error code.
| Signal | (number) The signal ID to enable or disable |
| Value | (boolean) True to enable the signal, false to disable it |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetSignalState | ( | name | , |
| val | , | ||
| inst | ) |
Set the state of a signal by signal ID.
Gets the signal handle via w.GetSignalHandle() and sets the signal state via mc.mcSignalSetState(). Returns an error if the signal name is not a number, if the value is not a number or boolean, or if the signal handle cannot be obtained.
| name | (number) The signal ID whose state is to be set |
| val | (number|boolean) The desired signal state to write |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule SetSoftLimits | ( | OnOff | , |
| inst | ) |
Enable or disable soft limits for all coordinated axes.
Reads the current OSIG_SOFTLIMITS_ON signal state and, if the requested state differs from the current state, iterates through all axes (X through MC_MAX_AXES-1) calling mc.mcSoftLimitSetState() for each. Logs the action taken. Does nothing if the requested state already matches the current state.
| OnOff | (boolean) True to enable soft limits, false to disable |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetStatus | ( | log_msg | ) |
Set the Mach4 status bar message using mcCntlSetLastError.
Retrieves the currently selected instance via w.GetSelectedInstance() and writes the provided message to the Mach4 last error display via mc.mcCntlSetLastError(). Non-string values are converted to string via tostring() before display.
| log_msg | (string) The status message to display. Non-string values are converted via tostring() |
| WrapperModule SetStopStatus | ( | inst | ) |
Record the current machine stop/disable counter value for later comparison.
Reads the current value of the CmdStopAndDisable register from "core/inst" and writes it to the MachMotion/mm_StopStatus register. This snapshot is later compared by w.CheckStopStatus() to detect if the machine has been disabled between calls.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetStopStatusAll | ( | ) |
Update the stop status register for all available Mach4 instances.
Iterates over all instances from 0 to GetInstanceCount()-1 and calls w.SetStopStatus() for each one to record the current CmdStopAndDisable value.
| WrapperModule SetToolChangeStatus | ( | attribute | , |
| value | , | ||
| spindle | , | ||
| inst | ) |
Set a named tool change status attribute for a spindle.
Delegates to user.UserSetToolChangeStatus() if a user override exists. Otherwise, sends a SetAttribute command via w.RegSendCommand() to the MachMotion cmd_ToolChangeStatus register, formatted as "SetAttribute;{attribute},{value};{spindle}". Returns an error if the attribute name is nil or not a string, or if the register command fails.
| attribute | (string) The name of the tool change status attribute to set |
| value | (any) The value to set for the attribute |
| spindle | (number|nil) The spindle number. Defaults to 1 if not a number |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetToolSetterAutoName | ( | name | ) |
Set the auto tool setter selection by name and persist the change to the profile.
Retrieves all configured auto tool setters via w.GetAllAutoToolSetters(), validates that the given name exists in the list, then writes the name to the AutoSetterSelection OEM parameter string via w.eSetOEMParamValueString(). Raises an error if the name is not found.
| name | (string) The name of the auto tool setter to select |
References name().
| WrapperModule SetToolSetterHeight | ( | ToolSetterName | , |
| Height | ) |
Set the height of a named tool setter and persist the change to the profile.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter(), updates the Height field to the given Height value, then writes the updated configuration back to the profile via WriteToolSetter().
| ToolSetterName | (string) The name of the tool setter whose height to set |
| Height | (number) The height value to store for the tool setter |
| WrapperModule SetToolSetterManualName | ( | name | , |
| inst | ) |
Set the manual tool setter selection by name and persist the change to the profile.
Retrieves all configured manual tool setters via WrapperModule.GetAllManualToolSetters(), validates that the given name exists in the list, then writes the name to the ManualSetterSelection OEM parameter string via w.eSetOEMParamValueString(). Raises an error via w.Error() if the setter name is not found in the configured setters.
| name | (string) The name of the manual tool setter to select |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References name().
| WrapperModule SetToolSetterPosition | ( | AutoManual | , |
| Position | ) |
Set the Z position of a named tool setter and persist the change to the profile.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter(), updates the ZPosition field to the given Position value, then writes the updated configuration back to the profile via WriteToolSetter().
| ToolSetterName | (string) The name of the tool setter whose Z position to set |
| Position | (number) The Z position value to store for the tool setter |
| WrapperModule SetToolSetterPosition | ( | ToolSetterName | , |
| Position | ) |
Set the Z position of a named tool setter and persist the change to the profile.
Retrieves the tool setter configuration table for ToolSetterName via GetToolSetter(), updates the ZPosition field to the given Position value, then writes the updated configuration back to the profile via WriteToolSetter().
| ToolSetterName | (string) The name of the tool setter whose Z position to set |
| Position | (number) The Z position value to store for the tool setter |
| WrapperModule SetToolTableUserValue | ( | fieldName | , |
| val | , | ||
| tool | , | ||
| inst | ) |
Set a numeric user field value in the tool table for a specified tool.
Wraps mc.mcToolSetDataExDbl() with error handling and instance management. If tool is nil, retrieves the current tool number via mc.mcToolGetCurrent(). Does nothing and returns success if the tool number is 0 (no tool loaded). Both number and boolean values are accepted for val.
| fieldName | (string) The name of the user field to write |
| val | (number|boolean) The numeric or boolean value to write to the field |
| tool | (number|nil) The tool number to write to. If nil, uses the current tool |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetToolTableUserValue_Screen | ( | value | , |
| field_name | , | ||
| tool_number | , | ||
| ... ) |
Set a numeric user field value in the tool table from a screen chunk context.
Adapter function for calling SetToolTableUserValue() from screen controls where values arrive as strings and tool_number may be passed as -1 to indicate "current tool". Converts value to a number via tonumber() before delegating to w.SetToolTableUserValue(). Passing -1 as tool_number is treated as nil (use current tool).
| value | (string|number) The value to set, converted to number internally |
| field_name | (string) The name of the user field to write |
| tool_number | (number|nil) The tool number, or -1 to use the current tool |
| ... | (any) Additional arguments forwarded to w.SetToolTableUserValue() |
| WrapperModule SetToolTableUserValueString | ( | fieldName | , |
| val | , | ||
| tool | , | ||
| inst | ) |
Set a string user field value in the tool table for a specified tool.
Wraps mc.mcToolSetDataExStr() with error handling and instance management. If tool is nil, retrieves the current tool number via mc.mcToolGetCurrent(). Does nothing if the tool number is 0 (no tool loaded). Both fieldName and val must be strings.
| fieldName | (string) The name of the user field to write |
| val | (string) The string value to write to the field |
| tool | (number|nil) The tool number to write to. If nil, uses the current tool |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SetValueBit | ( | value | , |
| BitIdx | , | ||
| state | ) |
Set or clear the bit at a zero-indexed position in a value.
Sets or clears the bit at the zero-indexed position BitIdx in the given value using bitwise operations. The state parameter defaults to true if nil. Converts non-boolean state values via w.ToBoolean(). Returns an error if BitIdx is outside the valid range [0, MAX_BITS).
| value | (number) The integer value whose bit is to be set or cleared |
| BitIdx | (number) The zero-indexed bit position to modify (must be in [0, MAX_BITS)) |
| state | (boolean|nil) The desired bit state - true to set, false to clear. If nil, defaults to true |
| WrapperModule SetVersionStrings | ( | _module | , |
| url_svn | , | ||
| rev_svn | ) |
Extract and store SVN revision and URL keyword strings for a Lua module.
Parses the SVN keyword substitution strings for URL and Revision, extracts the module filename relative to the Modules directory and the revision number, and stores them as VERSION_<filename> in the provided module table. The SVN keywords must be enabled (svn:keywords URL and Revision) on the calling file for the substitution strings to contain meaningful values.
| _module | (table) The Lua module table in which to store the version string |
| url_svn | (string) The SVN URL keyword string (e.g., "$URL: https://... $") |
| rev_svn | (string) The SVN Revision keyword string (e.g., "$Revision: 12345 $") |
| WrapperModule SetWarningMessage | ( | Message | , |
| TimeOut | , | ||
| EveryWhere | , | ||
| Title | , | ||
| Size | , | ||
| inst | ) |
Display a warning message notification in the GMS notification bar.
Creates a GMS notification via w.CreateGMSNotification() with the given message and title. The TimeOut parameter controls display duration: false means indefinite (-1), true uses the WARNING_MESSAGE_TIME constant, and a positive number specifies milliseconds. In multi-instance configurations, the instance number is automatically appended to the title. If EveryWhere is true, the message is also sent to mc.mcCntlSetLastError(). Newline characters are stripped from the message.
| Message | (string) The warning message text to display |
| TimeOut | (boolean|number|nil) Display duration: false or nil for indefinite, true for default time, or a positive number in milliseconds |
| EveryWhere | (boolean|nil) If true, also sets the Mach4 last error message. If nil, defaults to false |
| Title | (string|nil) The notification title text. If nil, defaults to an empty string |
| Size | (number|nil) Font size (-1, -2, -3 for predefined sizes, or a positive number). If nil, defaults to -1 |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule ShowNetworkAdapters | ( | ) |
Display all network adapter names and IP addresses in a message box.
Calls w.GetNetworkAdapters() to retrieve the list of adapters and formats them as "AdapterName - IP\n" lines. If an error occurs or no adapters are found, displays an appropriate message. Shows the result in a wxMessageBox with an information icon.
| WrapperModule SignalMap | ( | Signal | , |
| Device | , | ||
| IoName | , | ||
| ActiveLow | , | ||
| inst | ) |
Map a signal to an I/O point, enable it, and configure its active-low polarity.
Gets the signal handle via w.GetSignalHandle() and the I/O handle via w.GetIoHandle(), then unmaps the signal via mc.mcSignalUnmap(), maps it to the I/O handle via mc.mcSignalMap(), enables the signal via mc.mcSignalEnable(), and sets the active-low polarity via mc.mcSignalSetActiveLow(). Returns an error at any step that fails.
| Signal | (number) The signal ID to map |
| Device | (string) The device name under which the I/O point is registered |
| IoName | (string) The name of the I/O point to map the signal to |
| ActiveLow | (boolean) If true, the signal is active low; if false, active high |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule Sleep | ( | msTime | , |
| sleep_per_iteration | , | ||
| IgnoreStopStatus | ) |
Pause execution for specified milliseconds while monitoring machine state.
-------------------— Sleep Wrapper -------------------—
Blocks execution for the specified duration while periodically checking if the machine has been disabled (unless IgnoreStopStatus is true). Behavior differs based on execution context:
| msTime | (number) Total sleep duration in milliseconds. Must be > 0 |
| sleep_per_iteration | (number|nil) Sleep interval per check cycle in ms. If nil, defaults to min(20, msTime) |
| IgnoreStopStatus | (boolean|nil) If true, skip machine disable checking. If nil, defaults to false |
| sortFunction | ( | a | , |
| b | ) |
Default sort comparator used by GetKeysSortedByValue to sort keys by their associated table values.
Compares two keys (a and b) by looking up their values in the enclosing tbl table and returning true if tbl[a] < tbl[b]. This is a closure created inside GetKeysSortedByValue when no external sortFunction is provided.
| a | (any) First key to compare |
| b | (any) Second key to compare |
Referenced by GetKeysSortedByValue().
| WrapperModule SpindleSpeedVariation | ( | on_off | , |
| inst | ) |
Enable or disable Spindle Speed Variation (SSV).
Controls Spindle Speed Variation by writing to Mach4 parameter 1940. When enabled, the control continuously varies the spindle speed within a range defined by parameters 1941 (variation amount in RPM) and 1942 (duty cycle in seconds). The operation is wrapped in a protected call; errors are logged via w.FunctionError() but do not propagate.
| on_off | (boolean) True to enable SSV, false to disable SSV |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule SpindleSpeedVariationToggle | ( | ) |
Toggle Spindle Speed Variation (SSV) between on and off states.
Reads the current state of Spindle Speed Variation and inverts it by calling SpindleSpeedVariation() with the opposite boolean value.
| WrapperModule string split | ( | str | , |
| sSeparator | , | ||
| nMax | , | ||
| bRegexp | ) |
Split a delimited string into an array of substrings.
Splits str on each occurrence of sSeparator and returns the pieces as an array. Supports a maximum split count via nMax and optional regular expression separators via bRegexp. An empty string input returns an empty array. The separator must not be an empty string. Taken from the Lua-users wiki SplitJoin page (true Python semantics for split).
| str | (string) The string to split |
| sSeparator | (string) The separator between pieces. Must not be an empty string |
| nMax | (number|nil) The maximum number of splits to perform. If nil, splits all occurrences |
| bRegexp | (boolean|nil) If true, sSeparator is treated as a Lua pattern. Defaults to plain text |
| WrapperModule SplitVersionString | ( | version_string | ) |
Split a period-or-comma-delimited version string into an array of pieces.
Iterates through all period- or comma-delimited tokens in version_string using string.gmatch. Each token is converted to a number via tonumber(); if conversion fails, the raw string token is kept. The resulting pieces are collected into an array and returned.
| version_string | (string) A period-or-comma-delimited version string (e.g., "4.2.0.4310") |
| WrapperModule SrcLoc | ( | ) |
Return both the source file name and line number of the immediate caller.
Convenience wrapper that calls GetCurrFileName(3) and GetCurrLineNo(3) and returns both values as a pair. Intended to be used inline as arguments to functions like AlarmMessage() that accept a filename and line number for context.
| WrapperModule StartCustomCntlDwellBar | ( | dwellbartable | ) |
Start the custom CNC dwell bar with the given configuration table.
Forwards to m.screen.StartCustomCntlDwellBar() if the screen module and method are available. If no screen module is present, the call is silently ignored. The dwellbartable parameter provides configuration such as duration and display text to the screen implementation.
| dwellbartable | (table) Configuration table for the dwell bar (content depends on screen implementation) |
| WrapperModule Averager stdev | ( | ) |
Calculate the standard deviation of the sampled y-values.
Returns the square root of variance() for the current sample window. Applies Bessel's correction (degrees of freedom = 1) via the underlying variance() call.
| mean_value | (number|nil) The mean of the sampled y-values. If nil, computed internally via variance() |
| WrapperModule Averager stdev_x | ( | ) |
Calculate the standard deviation of the x-index sequence for the current sample window.
Returns the square root of variance_x(). The x-indices are the integer sequence (1, 2, ..., n) representing positions of the stored data points.
| mean_x | (number|nil) The mean of the x-index sequence. If nil, computed internally via variance_x() |
| WrapperModule Jogger Stop | ( | ) |
Stop the axis jog using the appropriate stop command for the current jog mode.
Checks whether the Jogger is currently jogging and issues the correct stop API call based on the active jog mode: velocity stop for Continuous and Feedrate modes, increment stop for Incremental mode, and ABS stop for ABS mode. Logs each stop action. Does nothing if the axis is not currently jogging.
| WrapperModule StopCustomCntlDwellBar | ( | ) |
Stop the custom CNC dwell bar by forwarding to the screen module or writing -1 to the OEM parameter.
If m.screen.StopCustomCntlDwellBar() is available, delegates to it. Otherwise, writes -1 to the CustomCntlDwellBar OEM parameter directly to signal the dwell bar is inactive.
| WrapperModule Jogger StopWait | ( | ) |
Stop the axis jog and wait until motion has fully ceased.
Calls Stop() to initiate the stop command appropriate for the current jog mode, then calls Wait() to block until the axis has come to a complete stop.
| WrapperModule StoreInstance | ( | ) |
Save the current active Mach4 instance for later restoration.
Saves the current value of MINSTANCE into WrapperModule.STORED_INST, calls w.FunctionCompleted() with the stored instance value, and returns the stored instance number. Used in conjunction with w.RestoreInstance() to bracket operations that may change the active instance context (e.g., modal dialog display).
| WrapperModule StringFormat | ( | commandString | , |
| number | , | ||
| format_string | , | ||
| postString | , | ||
| debugging | ) |
Format a number with a G-code command prefix and optional suffix into a string.
-------------------------------— GCode String Formatting Wrapper --------------------------—
Combines a command string prefix, a formatted numeric value, and an optional suffix string into a single output string. The number is formatted using the provided format string (e.g., "%0.4f"). If commandString is nil or empty, only the formatted number (and suffix) is returned. Useful for constructing G-code lines programmatically.
| commandString | (string|nil) The G-code command prefix (e.g., "G90 G00 Z"). If nil, defaults to "" |
| number | (number) The numeric value to format and append after the command string |
| format_string | (string|nil) A printf-style format string for the number (e.g., "%0.4f"). If nil, defaults to "%0.6f" |
| postString | (string|nil) An optional suffix appended after the formatted number. If nil, defaults to "" |
| debugging | (boolean|nil) If true, displays debug message boxes during execution |
| WrapperModule StripGCodeLine | ( | Line | , |
| Keywords | ) |
Remove specified G-code word/value pairs (by keyword) from a G-code line string.
Searches the line for each keyword in Keywords (e.g., "X", "Y", "Z") followed by a numeric value matching the internal gnumber_pattern. Removes each matched word-value pair from the line. Both uppercase and lowercase versions of each keyword are checked. Returns the total number of substitutions made as a fourth return value.
| Line | (string) The G-code line from which to strip keyword-value pairs |
| Keywords | (table) An array of keyword strings to remove (e.g., {"X", "Y", "Z"}) |
| WrapperModule StripModals | ( | Line | , |
| Modals | ) |
Removes specified modal G-code and M-code commands from a G-code line.
This function strips modal commands (G-codes and M-codes) from a G-code line string. It handles both integer modals (e.g., G0, G1, M3) and decimal modals (e.g., G43.1). The function supports both uppercase and lowercase modal codes and handles leading zeros. Invalid modals that cannot be parsed are appended to the line with an error notation.
| Line | (string) The G-code line from which to strip modals |
| Modals | (table) An array of modal strings to remove (e.g., {"G0", "G1", "M3"}) |
| WrapperModule TableLength | ( | tbl | ) |
Count the number of key-value pairs in a table using pairs() iteration.
Iterates over all entries in the table using pairs() to count them, including non-integer and non-sequential keys that the # length operator would miss.
| tbl | (table) The table whose entries are to be counted |
| WrapperModule TabletoCSV | ( | tt | ) |
Convert a sequential table of values into a comma-separated CSV string.
Iterates over the array table using ipairs(), escapes each value using w.EscapeCSV(), and concatenates them with commas. The leading comma from the first element is removed before returning.
| tt | (table) Sequential array table of values to convert to CSV format |
| WrapperModule TableToString | ( | tbl | , |
| indent | , | ||
| terse | , | ||
| linesep | , | ||
| depth | , | ||
| seen | ) |
Convert a table to a human-readable string representation resembling JSON.
Recursively formats a table and its contents into a structured string. Handles nested tables with indentation, prevents infinite recursion from cyclic table references via a 'seen' tracking table, and supports terse (single-line) output. Non-table inputs return a type/value string. Nil input returns "(nil)".
| tbl | (table|any) The table to stringify. Non-table values return a formatted type/value string |
| indent | (string|nil) Current indentation prefix string. If nil, defaults to "" |
| terse | (boolean|nil) If true, omits newlines and indentation for compact single-line output |
| linesep | (string|nil) Line separator string. If nil, defaults to "\n" |
| depth | (number|nil) Maximum recursion depth. 0 means unlimited depth. If nil, defaults to 0 |
| seen | (table|nil) Internal cycle-detection table. Pass nil on first call |
| WrapperModule TemporaryMachineState | ( | actions | ) |
Create a temporary machine state object that saves and restores the machine state.
Calls mc.mcCntlMachineStatePush() to save the current machine state, then executes each action in the provided actions list. String actions are executed as G-code via mc.mcCntlGcodeExecuteWait(). Function actions are called with the instance as their argument. The returned object's Revert() method restores the saved machine state. If actions is not a table, it is automatically wrapped in a table for uniform processing.
| actions | (string|function|table|nil) One or more actions to apply after saving state. May be a single string (G-code), a single function, or a table of strings/functions. If nil, no actions are executed after pushing state. |
| WrapperModule TimeToMove | ( | distance | , |
| units | ) |
Calculate the time in milliseconds required to travel a given distance at the current feed rate.
Reads the programmed feed rate via GetProgrammedFeedRate(), adjusts it by the current Feed Rate Override (FRO) percentage, reads the current unit system, converts the given distance to current units if needed, and computes the travel time as: (distance / feedrate) * 60 * 1000. Returns an error if the instance is nil, distance is not a number, or if any underlying API call fails.
| distance | (number) The distance to travel (interpreted in the unit system specified by units) |
| units | (number|nil) The unit system for distance: 200 for inches, 210 for mm. If nil, uses current units |
| WrapperModule ToBoolean | ( | value | ) |
Convert any value to a boolean using Mach4 convention rules.
Converts values of various types to boolean according to the following rules:
| value | (number|string|boolean|nil) The value to convert to boolean |
| WrapperModule toint | ( | number | ) |
Convert a value to a Lua integer, attempting intelligent type coercion.
Attempts to convert the input to an integer through multiple strategies:
| number | (number|string) The value to convert to an integer |
| WrapperModule array tointeger | ( | tbl | ) |
Convert all elements of an array to integers using math.tointeger().
Iterates through all elements of tbl using ipairs and converts each element to an integer via math.tointeger(). Returns a new table containing the converted values. Useful for converting string-numeric arrays (e.g., from CSV data) to integer arrays.
| tbl | (table) An array of values to convert to integers |
| WrapperModule tointstring | ( | number | ) |
Convert a value to an integer string, rounding floats to the nearest integer.
If the input is a string, attempts to parse it as a base-10 number first. If the input is a float, rounds to the nearest integer using math.floor(0.5 + number). If the input is already an integer, converts it directly to a string via tostring(). If the string cannot be parsed as a number, returns the original string unchanged.
| number | (number|string) The value to convert to an integer string |
| WrapperModule tonumber | ( | number | , |
| format_number | ) |
Convert a value to a formatted number with specified decimal precision.
Formats the input as a fixed-point decimal string using string.format(), then converts it back to a number via tonumber(). Returns nil with an error message if the input is nil. The format_number parameter controls the number of decimal places.
| number | (number|string) The value to format and convert |
| format_number | (number|nil) Number of decimal places (0-n). If nil, defaults to 6 |
References format_number().
| WrapperModule DbgCheckPoint tostring | ( | ) |
Format the checkpoint state as a human-readable multi-line string.
Retrieves all checkpoint IDs ordered by most-recent access (using w.GetKeysSortedByValue() on self.recent), then formats each entry as " id (value, msg)". The function name is included as the first line. Useful for including checkpoint context in error messages.
| WrapperModule tostring | ( | number | , |
| format_number | ) |
Convert a number to a string with specified decimal precision, removing scientific notation.
-— Number to String Formatting Wrapper ----—
This function formats numeric values as fixed-point decimal strings. If the input is already a string, it returns unchanged. If nil, returns the string "nil". The function prevents scientific notation (e.g., 1e-5) by using fixed-point formatting with configurable precision.
| number | (number|string|nil) The value to convert. Can be number, string, or nil |
| format_number | (number|nil) Number of decimal places (0-n). If nil, defaults to 6 |
References format_number().
| WrapperModule Averager trend | ( | ) |
Calculate the trend line value using least squares linear regression.
Computes the slope (B) and intercept (a) of the best-fit line through the sampled data points using the LSM (Least Squares Method) regression formula. Because points are stored in reverse order, the slope is inverted after calculation. Returns the y-value at x=1 (the most recent point on the trend line). Falls back to the mean if insufficient data exists or if statistical values are zero or negative.
| WrapperModule UnMapMotorsFromAxis | ( | AxisID | , |
| MotorID | , | ||
| inst | ) |
Unmap a motor (or all motors) from an axis and disable the axis if no motors remain.
Unmaps a specific motor from its parent axis, or all motors from an axis if MotorID is -1. First looks up the motor's current parent axis via GetMotorParentAxisID() and calls mc.mcAxisUnmapMotor() or mc.mcAxisUnmapMotors() accordingly. After unmapping, checks whether any motors remain mapped to the axis via GetAxisChildMotorID(); if none remain, disables the axis via mc.mcAxisEnable(). Raises an error via w.Error() if AxisID or MotorID are invalid.
| AxisID | (number) The axis ID constant (e.g., mc.X_AXIS) to unmap motors from |
| MotorID | (number) The motor ID to unmap, or -1 to unmap all motors from the axis |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule DbgCheckPoint update_recent | ( | ) |
Update the recency tracking table for the given checkpoint id.
Increments the recency counter for all existing checkpoint ids, then sets the counter for the current id to 0 (most recent). This allows checkpoint ids to be sorted by access recency.
| id | (any) The checkpoint identifier whose recency is being updated |
| WrapperModule UpdateCycleStartPressedFlag | ( | ) |
Update the Cycle Start Pressed Flag, resetting it if its active time has elapsed.
Checks whether the CycleStartPressedFlag is currently active. If active, calculates the elapsed time since it was set and calls ResetCycleStartPressedFlag() if the elapsed time exceeds the configured OnTime (default: 800 ms). Intended to be called periodically from a screen update loop.
| WrapperModule Jogger UpdateFeedrate | ( | ) |
Update the active jog feedrate if rapid override is enabled.
If use_rapid_ov is true, recalculates the effective feedrate via CalculateFeedrate() and updates the active jog feedrate via mcJogSetFeedRate only if the rate has changed by more than 0.01 units/minute. Does nothing if rapid override is not active.
| WrapperModule debug UpdateFunctionNameMap | ( | tables | , |
| dont_clear_cache | ) |
Rebuild the cached mapping of function objects to qualified name strings.
Wraps w.debug._UpdateFunctionNameMap() in a pcall to prevent errors from propagating. If dont_clear_cache is true, appends to the existing cache rather than clearing it first. If tables is nil, rebuilds using the default set of global module tables (w, m, h, mb, etc.). Logs any errors via w.LogF().
| tables | (table|nil) Table mapping display names to module tables to scan. If nil, uses the default global set |
| dont_clear_cache | (boolean|nil) If true, adds to the existing cache without clearing it. If nil, clears the cache first |
| WrapperModule UpdateGMSClass | ( | Handle | , |
| Class | ) |
Update the class (severity level) of an existing GMS global message.
Sends a "MonitorClass" command to the GMS plugin via w.SendGMSCommand() with the handle and new class value. If the class argument is not already a number, it is converted via w.GetGMSClassNumber() which maps strings like "ALARM", "WARNING", "NOTICE", "PROCESS" to their corresponding numeric values.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| Class | (number|string) The new class value - either a numeric class code or a string such as "Alarm", "Warning", "Notice", or "Process" |
| WrapperModule UpdateGMSDescription | ( | Handle | , |
| Text | ) |
Update the description text of an existing GMS global message.
Sends a "MonitorDescription" command to the GMS plugin via w.SendGMSCommand() with the handle and new text. The description is the secondary text shown below the title in the GMS notification dialog.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| Text | (string) The new description text to display in the message dialog |
| WrapperModule UpdateGMSTitle | ( | Handle | , |
| Text | ) |
Update the title text of an existing GMS global message.
Sends a "MonitorTitle" command to the GMS plugin via w.SendGMSCommand() with the handle and new text. The title is the primary text shown in large, bold letters in the GMS notification dialog.
| Handle | (number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage() |
| Text | (string) The new title text to display in the message dialog |
| WrapperModule UpdateNotification | ( | Identifier | , |
| Text | ) |
Update the text of an existing GMS notification.
Sends an "UpdateNotification" command to the GMS plugin via w.SendGMSCommand() with the identifier and new text formatted as a pipe-delimited string. The identifier must be a valid positive numeric handle previously returned by w.CreateGMSNotification() or w.CreateGMSDialog(). Does nothing if the identifier is invalid or the text is empty.
| Identifier | (number) The GMS notification handle returned by w.CreateGMSNotification() or w.CreateGMSDialog() |
| Text | (string) The new text to display in the notification |
| UI UpdatePleaseWaitDialog | ( | ) |
Poll the active wait condition and close the dialog if the condition is met or an error occurs.
This timer callback is called periodically (every 50ms) by the PleaseWait dialog timer. Checks for Mach shutdown, optional m.PleaseWaitDialogTimer(), then evaluates the active WaitType condition (MachState, Signal, IO, Register, FileLoading, TimeDelay, OEMParamSig, Function, DryRun, TimeDelayOrCycleStartPressedFlag). Calls UI.ClosePleaseWaitDialog(1) on success or UI.ClosePleaseWaitDialog(-1) on error/disable. Also handles Timeout and CheckStopStatus checks. Returns false while still waiting, or true/non-false when closing.
| WrapperModule UpdateRecentCSVs | ( | filename | ) |
Update the list of recently used CSV files stored in the Mach4 profile.
Maintains a list of up to 10 recently used CSV filenames in the Mach4 profile under the "RecentCSVFiles" section. If the filename is already in the list, it is moved to position 1. If it is new, all existing entries are shifted down and the new filename is inserted at position 1. The updated list is written back to the profile via mc.mcProfileWriteString().
| filename | (string) The full path to the CSV file to add or promote in the recent files list |
| WrapperModule UpdateSelectedInstance | ( | ) |
Read the selected Mach4 instance from the register and update the cache.
Reads the "core/global/SelectedInstance" register via w.GetRegValue(), defaulting to instance 0 if the read fails. Raises an error via w.Error() if the register read returns false. Stores the result in WrapperModule.SELECTED_INST and returns it.
| WrapperModule UpdateToolChangerInstance | ( | ) |
Update the cached tool changer instance value from the current OEM parameter.
Reads the "ToolChangerSingleInstance" OEM parameter string value via w.GetOEMParamValueString(). If the value is "Yes", sets the cached instance to 0; otherwise sets it to the currently selected instance via w.GetSelectedInstance(). Stores the result in the "MachInstance" cache under the key "ToolChangerSingleInstance". Raises an error via w.Error() if the OEM parameter cannot be read.
| UpdateWaitOnCondition | ( | ) |
Poll the current wait condition and return a status code indicating whether it has been met.
This is an inner polling function defined inside WrapperModule._WaitOnCondition(). It evaluates the active WaitType condition (MachState, Signal, IO, Register, FileLoading, TimeDelay, OEMParamSig, Function, DryRun, etc.) on each call. Returns 1 when the condition is met, -1 when an error or machine disable is detected, -10 when CheckStopStatus has been incremented, -20 on timeout, and false when the condition is not yet met and polling should continue. Also handles dwell bar updates for TimeDelayWithDwellBar variants.
| WrapperModule Jogger UseRapidOV | ( | ) |
Enable rapid rate override (RRO) scaling for this Jogger instance.
Sets the use_rapid_ov flag to true, causing subsequent CalculateFeedrate() and UpdateFeedrate() calls to scale the feedrate by the current rapid rate override percentage from mcCntlGetRRO.
| WrapperModule table val_to_str | ( | v | ) |
Convert a value to a compact string for use in table.repr() output.
String values are escaped (newlines replaced with
) and quoted, preferring single quotes when the string contains double quotes. Table values are recursively formatted via table.repr(). All other values are converted with tostring().
| v | (any) The value to convert to a string |
| WrapperModule table pretty val_to_str | ( | v | , |
| indent | , | ||
| has_key | ) |
Convert a value to an indented string for use in pretty-printed output.
Formats a value for human-readable output. String values are escaped and quoted (using single quotes if the string contains double quotes). Table values are recursively formatted via pretty.repr(). All other values are converted with tostring(). The has_key flag suppresses leading indentation when the value directly follows a key assignment.
| v | (any) The value to convert to a string |
| indent | (string|nil) The current indentation string. Defaults to "" if nil |
| has_key | (boolean|nil) If true, suppresses the leading indent prefix. Defaults to false |
| WrapperModule Averager variance | ( | ) |
Calculate the variance of the sampled y-values in the current window.
Computes the sample variance of the stored data points as sum((y_i - y_mean)^2) / (n - dof), where dof = 1 (Bessel's correction). Returns 0 if there are fewer than 2 points (n - dof <= 0).
| mean_value | (number|nil) The mean of the sampled y-values. If nil, computed via mean() |
| WrapperModule Averager variance_x | ( | ) |
Calculate the variance of the x-index sequence for the current sample window.
Computes the variance of the integer sequence (1, 2, ..., n) representing the x-indices of the stored data points. Uses simplified closed-form arithmetic for efficiency rather than iterating. Applies Bessel's correction (degrees of freedom = 1).
| WrapperModule VerifyAllAxesAreHomed | ( | IgnoreSaftyCheck | , |
| inst | ) |
Verify that all enabled axes are homed, respecting the HomingSafetyCheck OEM parameter.
Checks the HomingSafetyCheck OEM parameter to determine if homing verification is required. If enabled (or IgnoreSaftyCheck is true), iterates through all enabled axes across all instances in the instance table. For each axis, checks if it should be skipped via the IgnoreAxesHomingSafetyCheck parameter, then verifies the homed state via mc.mcAxisIsHomed(), calling MarkAxisAsHomedIfMotorsAreHomed() if needed. Returns a list of unhomed axes in the message if any are found.
| IgnoreSaftyCheck | (boolean) If true, forces the homing check regardless of the HomingSafetyCheck parameter |
| inst | (number) The Mach4 instance handle or instance table. If not provided, uses current instance |
| WrapperModule VerifyAllAxesAreHomedCached | ( | inst | ) |
Check if all enabled axes are homed using cached axis state data.
Reads the cached axis enabled and homed state from AXIS_ENABLED_INST and AXIS_IS_HOMED_INST tables for the specified instance. Returns false immediately if any enabled axis is not homed or if cached data is unavailable (nil). Does not make any API calls; relies entirely on pre-populated cache tables.
| inst | (number) The Mach4 instance handle. If not provided, uses current instance via w.GetUTI() |
| WrapperModule VerifyCacheExists | ( | category | ) |
Ensure that a named cache category exists in the WrapperModule cache.
Checks whether w.Cached[category] is nil. If it is, creates a new empty table and assigns it to w.Cached[category]. Returns the existing or newly created category table. This is boilerplate used by SetCache, GetCache, and IsCached to avoid nil-check repetition.
| category | (string) The cache category name to verify or create |
| WrapperModule VerifyMinimumMachVersion | ( | version_string | ) |
Verify that the running Mach4 version meets a specified minimum version requirement.
Splits both the current Mach4 version (obtained via mc.mcCntlGetVersion()) and the provided minimum version string into component arrays using SplitVersionString(). Compares components positionally from left to right. If a Mach4 component is less than the corresponding minimum component, returns false. Non-numeric components are compared as strings. If the Mach4 version has fewer components than the minimum, those positions are not checked.
| version_string | (string) The minimum required version as a period-delimited string (e.g., "4.2.0.4310") |
| WrapperModule Jogger Wait | ( | ) |
Block execution until the axis jog is complete.
Polls mcJogIsJogging and mcJogIsStopping until both return 0, indicating the axis has fully stopped. Behavior differs based on execution context:
| WrapperModule WaitForFileQueueResponse | ( | handle | , |
| check_func | , | ||
| inst | ) |
Block until a file queue command receives a reply or the machine is disabled.
Polls the LuaFileQueue for a reply to the given handle, sleeping for w.GetFileQueueSleepTime() milliseconds between checks via w.Sleep(). If w.Sleep() returns an error (e.g., machine disabled), cleans up the queue entry and returns false. An optional check_func callback is called after each sleep iteration. Returns when a reply is received or on error.
| handle | (string) The file queue command handle returned by w.PostToFileQueue() |
| check_func | (function|nil) Optional callback function called after each sleep interval. If nil, no callback is made |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
| WrapperModule WaitForIoState | ( | Device | , |
| IoName | , | ||
| State | , | ||
| Timeout | , | ||
| AlarmMessage | , | ||
| inst | ) |
Wait for an I/O point to reach a specified boolean state, with timeout and machine disable detection.
-------------------— Wait For I/O Wrapper -------------------—
Blocks execution until the I/O point Device/IoName equals State, or until the timeout expires, or until the machine is disabled. In screen chunk context, delegates to w.WaitOnCondition() with WaitType.IO. In M-code chunk context, polls the I/O state directly using a repeat loop with 2ms sleep intervals. Validates all input types and ranges before waiting.
| Device | (string) The device name containing the I/O point (e.g., "MachMotion") |
| IoName | (string) The I/O point name to monitor |
| State | (boolean) The desired I/O state to wait for (true or false) |
| Timeout | (number) Maximum wait time in milliseconds. Must be >= 0 |
| AlarmMessage | (string|nil) Custom message for timeout error. If nil, generates a default message |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References AlarmMessage().
| WrapperModule WaitForOEMParamSig | ( | Signal | , |
| State | , | ||
| Timeout | , | ||
| AlarmMessage | , | ||
| inst | ) |
Wait for an OEM parameter signal to reach a specified state with timeout and machine disable detection.
-------------------— Wait For OEM Signal Wrapper -------------------—
Blocks execution until the specified OEM parameter signal equals the desired state or the timeout expires, or until the machine is disabled. In screen chunk context, delegates to w.WaitOnCondition() with WaitType.OEMParamSig. In M-code chunk context, polls the OEM parameter signal directly in a repeat loop with 2ms sleep intervals. Validates all input types and ranges before waiting. Constructs human-readable messages for timeout, wait, and disable conditions.
| Signal | (string) The OEM parameter signal name to monitor |
| State | (boolean) The desired signal state to wait for (true or false) |
| Timeout | (number) Maximum wait time in milliseconds. Must be >= 0 |
| AlarmMessage | (string|nil) Custom alarm message. If nil, generates a default message from the signal description |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References AlarmMessage().
| WrapperModule WaitForRegisterValue | ( | Device | , |
| RegName | , | ||
| Value | , | ||
| Timeout | , | ||
| AlarmMessage | , | ||
| inst | ) |
Wait for a register value to equal a specified value, with timeout and machine disable detection.
-------------------— Wait For Register Wrapper -------------------—
Blocks execution until the value of Device/RegName equals Value, or until the timeout expires, or until the machine is disabled. In screen chunk context, delegates to w.WaitOnCondition() with WaitType.Register. In M-code chunk context, polls the register value directly using a repeat loop with 2ms sleep intervals. Validates all input types and ranges before waiting.
| Device | (string) The device name containing the register (e.g., "MachMotion") |
| RegName | (string) The register name to monitor |
| Value | (any) The expected register value to wait for |
| Timeout | (number) Maximum wait time in milliseconds. Must be >= 0 |
| AlarmMessage | (string|nil) Custom message for timeout error. If nil, generates a default message |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References AlarmMessage().
| WrapperModule WaitForSignal | ( | Signal | , |
| State | , | ||
| Timeout | , | ||
| AlarmMessage | , | ||
| inst | ) |
Wait for a signal to reach a specified state with timeout and machine disable detection.
-------------------— Wait For Signal Wrapper -------------------—
Blocks execution until the specified signal equals the desired state, or the timeout expires, or the machine is disabled. Validates all input types and ranges before waiting. Behavior differs based on execution context:
| Signal | (number) The signal handle to monitor |
| State | (boolean) The desired state (true or false) to wait for |
| Timeout | (number) Maximum time to wait in milliseconds. Must be >= 0 |
| AlarmMessage | (string|nil) Custom message for timeout alarm. If nil, generates default message from signal description |
| inst | (number) The Mach4 instance handle. If not provided, uses current instance |
References AlarmMessage().
| WrapperModule WaitOnCondition | ( | WaitType | , |
| WaitMessage | , | ||
| WaitDataInvert | , | ||
| WaitData1 | , | ||
| WaitData2 | , | ||
| WaitData3 | ) |
Wait for a specified condition without displaying a dialog, polling until the condition is met.
Wraps _WaitOnCondition() in a protected call via w.pcall(). Accepts either a table (WaitType table with 'Type', 'Message', 'Instance', etc.) or positional parameters. Supports all WaitType variants including MachState, Signal, IO, Register, FileLoading, TimeDelay, OEMParamSig, Function, DryRun, and dwell-bar variants. Unlike PleaseWaitDialog, this function does not create any UI. It uses w.Sleep(50) between polls and is suitable for M-code chunks.
| WaitType | (table|number) A WaitType table (preferred) or a numeric WaitType constant |
| WaitMessage | (string|nil) Message describing what is being waited for |
| WaitDataInvert | (boolean|nil) If true, inverts the condition check |
| WaitData1 | (any|nil) Primary wait data (signal handle, device name, mach state, etc.) |
| WaitData2 | (any|nil) Secondary wait data (register name, IO name, etc.) |
| WaitData3 | (any|nil) Tertiary wait data (expected value for register/IO comparisons) |
| WrapperModule WaitOnCycleStart | ( | Message | ) |
Pause G-code execution and wait for cycle start to resume.
Implements a configurable macro hold that blocks G-code execution and waits for the operator to press Cycle Start. The WaitOnCycleStartMode constant determines which Mach4 API is used: mode 1 uses mcCntlWaitOnCycleStart, mode 2 uses mcCntlToolChangeManual, and mode 3 uses mcFileHoldAquire with a polling loop checking machine state until it exits the macro hold states. Mode 2 is the current active mode due to a Mach4 build 3727 bug.
| Message | (string) The message to display to the operator while waiting |
| wrapper write | ( | self | , |
| stringdata | , | ||
| timeout | ) |
Write a string to the serial port.
Writes the specified string data to the serial port. Logs the data and timeout before writing. If the write fails, raises an error via w.Error(). The timeout parameter controls how long to wait for the write to complete.
| stringdata | (string) The string data to write to the serial port |
| timeout | (number|nil) Timeout in milliseconds. If nil, defaults to 0 (non-blocking) |
| wrapper writeBcc | ( | self | , |
| stringdata | , | ||
| timeout | ) |
Write a BCC-checksummed string to the serial port.
Computes the BCC checksum of the data string using bccCheckSum(), then writes the resulting checksummed string to the serial port via write().
| stringdata | (string) The data string to checksum and write |
| timeout | (number|nil) Timeout in milliseconds for the write operation. If nil, defaults to 0 |
| WrapperModule WriteCommandFile | ( | ) |
Write the current command, feedback, and action lists to all registered command receiver registers.
Retrieves all commands, feedbacks, and actions via w.GetAllCommands(), w.GetAllFeedbacks(), and w.GetAllActions(). Iterates over all register-type devices to find those with a "CommandReceiver" register, then writes a temporary INI file containing the active command names, feedback names, and action names. The file path is sent to each receiver register via w.api("mcRegSendCommand"). Command entries include all key-value fields from the command table. Counts for active commands, feedbacks, and actions are written under the "Active.Count", "Feedback.Count", and "Action.Count" keys.
| WrapperModule WriteCSV | ( | Table | , |
| FileName | , | ||
| WriteMode | ) |
Write a two-dimensional table of data to a CSV file.
Converts each row of the Table array into a comma-separated string and writes it to the file. Rows are separated by newlines. Nil rows are treated as having zero columns. The file is flushed and closed after writing. If WriteMode is nil, defaults to "w" (overwrite).
| Table | (table) Two-dimensional array table where Table[row][col] = value |
| FileName | (string) Full path to the CSV file to write |
| WriteMode | (string|nil) File open mode: "w" to overwrite, "a" to append. If nil, defaults to "w" |
| WrapperModule WriteLines | ( | Table | , |
| FileName | , | ||
| WriteMode | ) |
Write an array of strings to a file, with optional append mode.
Opens the file using the specified write mode and writes each element of the Table array sequentially. The file is flushed and closed after writing. If the file cannot be opened, returns an error. Elements are written as-is without additional newlines; callers should include newlines in the strings if needed (e.g., via w.AddLine()).
| Table | (table) Array of strings to write to the file |
| FileName | (string) Full path to the file to write |
| WriteMode | (string|nil) File open mode: "w" to overwrite, "a" to append. If nil, defaults to "w" |
| WrapperModule WriteTextFile | ( | TextString | , |
| FileName | , | ||
| WriteMode | ) |
Write a string to a text file, with optional append mode.
Opens the file using the specified write mode and writes the TextString. The file is flushed and closed after writing. If the file cannot be opened, returns an error.
| TextString | (string) The text content to write to the file |
| FileName | (string) Full path to the file to write |
| WriteMode | (string|nil) File open mode: "w" to overwrite, "a" to append. If nil, defaults to "w" |
| WrapperModule WriteToGMSLog | ( | Text | , |
| Class | ) |
Write a text entry to the GMS log without displaying any dialog.
Sends a "Log" command to the GMS plugin via w.SendGMSCommand() with the provided text and class number. The message is recorded in the GMS log as if it were a notification, but no dialog or notification bar entry is shown to the user. The Class parameter is converted to a numeric class code via w.GetGMSClassNumber().
| Text | (string) The text to write to the GMS log. Must be a non-empty string |
| Class | (number|string|nil) The message class - a numeric code or string such as "Alarm", "Warning", "Notice", or "Process". If nil, defaults to "NOTICE" |
| WrapperModule WriteToolSetter | ( | ini_table | ) |
Write a tool setter configuration table to the Mach4 profile and flush changes.
Deletes any legacy float-keyed section (e.g., "ToolSetter1.0") to fix Lua 5.3 tostring(float) naming issues. Initializes EndGoToPosition to "" if nil, then writes all tool setter fields (Name, AutoSetter, FixturesOffsets, FixtureOffsetMode, ProbeInput, DisableSoftlimits, Height, ZPosition, GoToPosition, EndGoToPosition) to the profile section identified by ini_table.SectionName. Calls w.FlushProfile() to persist changes.
| ini_table | (table) The tool setter configuration table to write. Required keys:
|
| WrapperModule wxMessageBox | ( | message | , |
| ... ) |
Display a wx modal message box and restore the Mach4 instance context on return.
Stores the current Mach4 instance via w.StoreInstance(), displays a wx message box via wx.wxMessageBox(), then restores the instance via w.RestoreInstance(). This ensures that modal dialogs do not corrupt the active Mach4 instance context. Converts non-string message values to string via tostring() before display.
| message | (string) The message text to display. Non-string values are converted via tostring() |
| ... | (any) Additional arguments passed to wx.wxMessageBox() (e.g., caption, style, parent) |
| WrapperModule Yield | ( | yield_events | ) |
Yield execution to the event loop one or more times, preventing UI freezing.
Allows the wxWidgets event loop to process pending events. In screen chunk context, calls wx.wxYield() for each iteration. In M-code chunk context, calls wx.wxMilliSleep(1). Restores the original instance context after yielding. Useful for keeping the UI responsive during short busy-wait loops without the overhead of a full Sleep() call.
| yield_events | (number|nil) Number of yield iterations to perform. If nil, defaults to 1 |