Mach Modules Documentation
Lua Module API Documentation
Loading...
Searching...
No Matches
WrapperModule.lua File Reference

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.
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.

Function Documentation

◆ AddLine()

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.

Parameters
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
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if the line was appended, false if Table was nil
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ AddOEMParamSignalToOutputIgnoreList()

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.

Parameters
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
Returns
(nil) No primary return value on success
(boolean) Success flag - true if completed successfully, false if signal not mapped or not an output
(string) Status message describing the result
See also
WrapperModule.AddOutputToOutputIgnoreLists() for the underlying list update implementation
Note
Documentation generated by AI on 2026-03-04

◆ AddOutputToAllOutputIgnoreLists()

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.

Parameters
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
See also
WrapperModule.AddOutputToOutputIgnoreLists() for adding to a custom set of lists
Note
Documentation generated by AI on 2026-03-04

◆ AddOutputToOutputIgnoreLists()

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.

Parameters
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
See also
WrapperModule.AddOutputToAllOutputIgnoreLists() for adding to all standard lists
Note
Documentation generated by AI on 2026-03-04

◆ AddToFunctionNameMap()

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.

Parameters
tables(table) Table mapping display names to module tables to scan for functions
See also
WrapperModule.debug.UpdateFunctionNameMap() for the full implementation
Note
Documentation generated by AI on 2026-03-04

◆ AddToListHistory()

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.

Parameters
filename(string) Full path to the history file to append to
list_line(string) The line to append. Newline characters are escaped before writing
Note
Duplicate consecutive entries (same as the last line) are silently ignored
See also
WrapperModule.ReadListHistory() which reads the history file used by this function
Note
Documentation generated by AI on 2026-03-04

◆ AddToolTableSimField()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ AddToolTableUserField()

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.

Parameters
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
-- Add a choice field for spindle rotation direction
w.AddToolTableUserField("SpindleRotation", "Spindle Rotation",
"Choice(Any=0,FWD Rotation=1,REV Rotation=2,No Rotation=3)")
VFD VFDCollection Add()
Add a VFD object to the collection.
Note
Documentation generated by AI on 2026-03-04

◆ AddToolTableUserFieldList()

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.

Parameters
field_list(table) A table whose keys are field names and values are tables with keys:
  • Description (string): The human-readable label shown in the tool table UI
  • FieldType (string): The field type spec string (e.g., "Choice(No=0,Yes=1)")
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No primary return value on success
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
-- Add two user fields at once
w.AddToolTableUserFieldList({
["ToolSoftLimitEnabled"] = {Description = "Use Tool Soft Limit", FieldType = "Choice(No=0,Yes=1)"},
["SpindleRotation"] = {Description = "Spindle Rotation", FieldType = "Choice(Any=0,FWD=1,REV=2)"},
})
See also
WrapperModule.AddToolTableUserField() to add a single user field
Note
Documentation generated by AI on 2026-03-04

◆ AlarmError()

WrapperModule AlarmError ( obj ,
FileName ,
Line ,
ForceAlarm  )

Construct and invoke a GMS alarm from obj.

WrapperModule.AlarmError

Parameters
obja string or object created by w.Error() (i.e. it's safe to use with nearly anything)
Note
Documentation generated by AI on 2026-03-03

◆ AlarmMessage()

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.

Parameters
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
See also
WrapperModule.AlarmError() for raising alarms from error objects
WrapperModule._AlarmMessage() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

Referenced by eWaitForOEMParamSig(), WaitForIoState(), WaitForOEMParamSig(), WaitForRegisterValue(), and WaitForSignal().

◆ api()

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, ...).

Parameters
...(any) The API function name (string) followed by all arguments to pass to the API function
Returns
(...) All non-error return values from the Mach4 API function
See also
WrapperModule.api_e() for the version supporting allowable error metadata
Note
Documentation generated by AI on 2026-03-04

◆ api_e()

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).

Parameters
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
Returns
(...) All non-error return values from the Mach4 API function (the trailing error code is consumed)
Warning
Raises a Lua error via w.Error() on any unhandled API error or Lua exception
See also
WrapperModule.api() for the simplified variant without metadata support
Note
Documentation generated by AI on 2026-03-04

◆ AppendActiveDialog()

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.

Parameters
dlg_name(string) The name key to register the dialog under
dlg(table) The dialog object to register
Note
This function is currently commented out in the codebase and not active
Documentation generated by AI on 2026-03-04

◆ AppendArgs()

WrapperModule AppendArgs ( suffix_table ,
... )

◆ AppendTables()

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.

Parameters
from(table) The source array table whose elements are to be appended
to(table) The destination array table to append elements into
Returns
(table) The destination table with appended elements
Note
Documentation generated by AI on 2026-03-04

◆ AppendToFile()

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.

Parameters
logfile(string|nil) Path to the log file. Defaults to 'wrapper.log' if nil
msg(string) The message to append to the file
Note
Documentation generated by AI on 2026-03-04

◆ ApplyMotorMappingsToMotionController()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) Returns whatever UpdateMotorMapping() returns
See also
WrapperModule.MapMotorsToAxis() to map a motor to an axis
WrapperModule.UnMapMotorsFromAxis() to unmap a motor from an axis
Note
Documentation generated by AI on 2026-03-04

◆ bccCheckSum()

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.

Parameters
str(string) The data string to compute the checksum for
Returns
(string) The single checksum character computed from the XOR of all bytes
(string) The original string concatenated with the checksum character
Note
Documentation generated by AI on 2026-03-04

◆ BoolToNumber()

WrapperModule BoolToNumber ( value )

Convert a boolean value to its numeric equivalent (1 or 0).

Parameters
value(boolean) The boolean value to convert
Returns
(number) 1 if value is truthy, 0 if value is falsy
Note
Documentation generated by AI on 2026-03-04

◆ bound()

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)).

Parameters
val(number) The value to clamp
minimum(number) The lower bound of the range
maximum(number) The upper bound of the range
Returns
(number) The clamped value, guaranteed to be in [minimum, maximum]
Note
Documentation generated by AI on 2026-03-04

◆ BriefParameterList()

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.

Parameters
stack_frame(number) The stack frame to inspect, relative to the caller of this function
Returns
(string) Comma-delimited string of "name(value)" pairs in parameter order, or "" if none
See also
WrapperModule.debug.GetParameters() for retrieving raw parameter data
Note
Documentation generated by AI on 2026-03-04

◆ BuildAPI()

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.

Parameters
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
Returns
(table) A ZeroBrane Studio-compatible API table structure
Note
Documentation generated by AI on 2026-03-04

◆ CalculateCarouselAngularDistances()

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.

Parameters
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)
Returns
(number) The clockwise angular distance in degrees (0 to 360)
(number) The counter-clockwise angular distance in degrees (0 to 360)
See also
WrapperModule.GetCarouselRotationWithLimits() which uses these distances for path selection
WrapperModule.IsCarouselPathViable() to check if a path stays within rotation limits
Note
Documentation generated by AI on 2026-03-04

◆ CalculateCarouselPathScore()

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.

Parameters
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)
Returns
(number) A weighted score for the path. Lower scores indicate better (more preferred) paths
See also
WrapperModule.IsCarouselPathViable() to check if a path is within rotation limits before scoring
WrapperModule.GetCarouselRotationWithLimits() which uses this score to select the best path
Note
Documentation generated by AI on 2026-03-04

◆ CalculateFeedrate()

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.

See also
WrapperModule.Jogger:UseRapidOV() to enable rapid override mode
WrapperModule.Jogger:UpdateFeedrate() to apply the calculated feedrate to an active jog
Note
Documentation generated by AI on 2026-03-04

◆ CalculateTotalAppliedOffset()

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.

Parameters
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
Returns
(number) The total applied coordinate offset for the axis in ToUnits
See also
WrapperModule.ConvertMachinePositionToPartPosition() which uses this offset for coordinate conversion
WrapperModule.ConvertPartPositionToMachinePosition() for the inverse conversion
Note
Documentation generated by AI on 2026-03-04

◆ CancelPleaseWaitDialog()

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.

Warning
This is a closure defined inside WrapperModule._PleaseWaitDialog(). MachState cancel will disable the machine. DryRun cancel will also reset the controller.
See also
UI.ClosePleaseWaitDialog() which is called at the end of each cancel branch
WrapperModule.PleaseWaitType for the wait type constants used in the dispatch
Note
Documentation generated by AI on 2026-03-04

◆ CHECK()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ CheckIfLicensed()

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.

Parameters
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
Returns
(boolean) True if the feature is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the deprecated plugin-based license checker
Note
Documentation generated by AI on 2026-03-04

◆ CheckStopStatus()

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.

Parameters
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
Returns
(number|nil) The current stop number value, or nil on error
(boolean) Success flag - true if machine is still enabled, false if disabled or error
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ clean_up()

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().

Note
This function is a local closure with no parameters and no return values
See also
WrapperModule.RegenerateToolPathDialog() for the enclosing function context
Note
Documentation generated by AI on 2026-03-04

◆ CleanUserCommandName()

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.

Parameters
command_name(string) The raw command name to sanitize
Returns
(string) The sanitized command name with special characters removed
Note
Documentation generated by AI on 2026-03-04

◆ ClearOEMParamValueBit()

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.

Parameters
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
Returns
(boolean) False on success (the cleared bit value), nil on error
(boolean) Success flag - true if the bit was cleared successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMParamValueBit() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ ClearOEMRegValueBit()

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.

Parameters
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
Returns
(boolean) False on success (the cleared bit value), nil on error
(boolean) Success flag - true if the bit was cleared successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMRegValueBit() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ ClearProbeFeedbackPositions()

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.

See also
WrapperModule.SetProbeFeedbackPositions() to store a specific probe feedback position
WrapperModule.GetProbeFeedbackPositions() to read a stored probe feedback position
Note
Documentation generated by AI on 2026-03-04

◆ ClearValueBit()

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.

Parameters
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))
Returns
(number|nil) The new value with the specified bit cleared, or nil on error
(boolean) Success flag - true if the bit was cleared successfully
(string) Status message describing the result
See also
WrapperModule.SetValueBit() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ close()

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.

Warning
This function raises an error and does not return if the port cannot be closed
Note
Documentation generated by AI on 2026-03-04

◆ CloseActiveDialogs()

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.

Note
This function is currently commented out in the codebase and not active
Documentation generated by AI on 2026-03-04

◆ CloseGMSMessage()

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.

Parameters
Handle(number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage()
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.CloseGMSNotification() for closing dialog/notification handles
WrapperModule.CreateSystemGlobalMessage() for creating GMS monitor messages
Note
Documentation generated by AI on 2026-03-04

◆ CloseGMSNotification()

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.

Parameters
Handle(number|string) The GMS notice handle returned by w.CreateGMSDialog() or w.CreateGMSNotification()
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.CloseGMSMessage() for closing monitor handles from CreateSystemGlobalMessage
WrapperModule.CreateGMSNotification() for creating notifications
Note
Documentation generated by AI on 2026-03-04

◆ ClosePleaseWaitDialog() [1/2]

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.

Parameters
EndModalCode(number|nil) The modal result code to pass to MainPleaseWaitDialog:EndModal(). Defaults to 0
Returns
(boolean) True if the dialog was closed successfully, false if an error occurred
Warning
This is a closure defined inside WrapperModule._PleaseWaitDialog() and is only valid during that function's execution
See also
UI._ClosePleaseWaitDialog() for the actual dialog close implementation
Note
Documentation generated by AI on 2026-03-04

◆ ClosePleaseWaitDialog() [2/2]

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.

Parameters
EndModalCode(number|nil) The modal result code. Defaults to 0 if nil
Returns
(boolean) Always returns true on successful completion
Warning
This is a closure defined inside WrapperModule._PleaseWaitDialog() and is only valid during that function's execution
See also
UI.ClosePleaseWaitDialog() which wraps this function with pcall error handling
Note
Documentation generated by AI on 2026-03-04

◆ concat()

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.

Parameters
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
Returns
(string) The concatenated string of all table elements separated by sep
Note
Documentation generated by AI on 2026-03-04

◆ ConfigureToolSpecificSoftLimits()

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.

Parameters
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.

See also
WrapperModule.IsToolTableUserField() to check whether a user field exists
WrapperModule.AddToolTableUserFieldList() to add user fields to the tool table
Note
Documentation generated by AI on 2026-03-04

◆ ConvertFromCurrentUnits()

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().

Parameters
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
Returns
(number|nil) The converted value in ToUnits, or nil on error
(boolean) Success flag - true if conversion completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.ConvertFromSetupUnits() for the inverse transformation
WrapperModule.GetMachSetupUnits() for the machine default unit system
Note
Documentation generated by AI on 2026-03-04

◆ ConvertFromImperialToCurrentUnits()

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.

Parameters
value(number) The value in imperial (inches) to convert
Returns
(number|nil) The value in current units, or nil on error
(boolean) Success flag - true if conversion completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.ConvertFromMetricToCurrentUnits() for the metric-to-current equivalent
WrapperModule.GetMachSetupUnits() for the machine unit system
Note
Documentation generated by AI on 2026-03-04

◆ ConvertFromMetricToCurrentUnits()

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.

Parameters
value(number) The value in metric (millimeters) to convert
Returns
(number|nil) The value in current units, or nil on error
(boolean) Success flag - true if conversion completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.ConvertFromImperialToCurrentUnits() for the imperial-to-current equivalent
WrapperModule.GetMachSetupUnits() for the machine unit system
Note
Documentation generated by AI on 2026-03-04

◆ ConvertFromSetupUnits()

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.

Parameters
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
Returns
(number|nil) The converted value in ToUnits, or nil on error
(boolean) Success flag - true if conversion completed successfully
(string) Status message describing the result
See also
WrapperModule.ConvertFromCurrentUnits() for the inverse transformation
WrapperModule.GetMachSetupUnits() for the machine default unit system
Note
Documentation generated by AI on 2026-03-04

◆ ConvertMachinePositionToPartPosition()

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().

Parameters
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
Returns
(number) The corresponding part-coordinate position in UnitSystem units
See also
WrapperModule.ConvertPartPositionToMachinePosition() for the inverse transformation
WrapperModule.CalculateTotalAppliedOffset() for the offset used in the conversion
Note
Documentation generated by AI on 2026-03-04

◆ ConvertPartPositionToMachinePosition()

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().

Parameters
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
Returns
(number) The corresponding machine-coordinate position in UnitSystem units
See also
WrapperModule.ConvertMachinePositionToPartPosition() for the inverse transformation
WrapperModule.CalculateTotalAppliedOffset() for the offset used in the conversion
Note
Documentation generated by AI on 2026-03-04

◆ CopyTables()

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.

Parameters
from(table) The source table whose entries are to be copied
to(table) The destination table to copy entries into
Returns
(table) The destination table with merged entries
(boolean) Success flag - always true
(string) Status message - "Copied tables"
Note
Documentation generated by AI on 2026-03-04

◆ CopyToClipboard()

WrapperModule CopyToClipboard ( data )

◆ covariance()

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.

Parameters
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()
Returns
(number) The covariance of x-indices and y-values, or 0 if no data points exist
See also
WrapperModule.Averager:mean_x() for the x-index mean calculation
WrapperModule.Averager:mean() for the y-value mean calculation
Note
Documentation generated by AI on 2026-03-04

◆ Create()

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.

Parameters
name(string|nil) A human-readable name for this function queue group. Defaults to "Unnamed Registrar" if nil
Returns
(table) A new FunctionQueue instance with Register, Execute, and Print methods
Note
Documentation generated by AI on 2026-03-04

◆ CreateCommand()

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.

Parameters
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
See also
WrapperModule.CreateSimpleCommand() for a convenience wrapper
WrapperModule.SaveUserCommand() for persisting a command to disk
Note
Documentation generated by AI on 2026-03-04

◆ CreateCommandActionOption()

WrapperModule CreateCommandActionOption ( name ,
func  )

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".

Parameters
name(string) The name key under which to register the action function
func(function) The action function to register
Note
Documentation generated by AI on 2026-03-04

References func(), and name().

◆ CreateCommandFeedbackOption()

WrapperModule CreateCommandFeedbackOption ( name ,
func  )

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".

Parameters
name(string) The name key under which to register the feedback function
func(function) The feedback function to register. Should return a boolean state
Note
Documentation generated by AI on 2026-03-04

References func(), and name().

◆ CreateFunctionFromCommand()

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:

  • "User Script": calls user.UserCommands[ActionOption]
  • "Output: Turn On/Off/Toggle": sets/toggles an output signal state
  • "Input: Turn On/Off/Toggle": sets/toggles an input signal state
  • "I/O: Turn On/Off/Toggle": sets/toggles an I/O point state
  • "Pre-Canned": calls m.CommandActions[ActionOption] Returns an empty no-op function if the command is not found or has no Action mapping.
    Parameters
    command_name(string) The name of the user command to convert to a function
    Returns
    (function) A callable function implementing the command's action. The function accepts (from_opr_panel, ...) parameters. Returns an empty function if command is not found
    See also
    WrapperModule.RunUserCommand() for executing a command by name directly
    Note
    Documentation generated by AI on 2026-03-04

◆ CreateGMSDialog()

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.

Parameters
Table(table) Configuration table with keys:
  • Class (string|nil): Message class - "Alarm", "Warning", "Notice", or "Process". Default: "Notice"
  • Title (string|nil): Title text shown in large bold letters. Default: ""
  • Description (string|nil): Body text shown below the title. Default: ""
  • Time (number|nil): Display duration in milliseconds (-1 for indefinite). Default: -1
  • CloseOnTimeout (number|nil): 1 to close when time expires. Default: 0
  • BackgroundColor (table|nil): RGB color table {r, g, b}. Default: {255, 255, 255}
  • HideCloseBtn (number|nil): 1 to hide the close button. Default: 0
  • ExtraLines (table|nil): Array of extra content panel tables, each with keys: Text, Title, Time, Close, Box, Size, Red, Green, Blue
Returns
(number|nil) The GMS notice handle for use with w.CloseGMSNotification(), or nil on error
(boolean) Success flag - true if the dialog was created successfully
(string) Status message from the GMS command response
See also
WrapperModule.CloseGMSNotification() for closing the dialog by handle
WrapperModule.CreateSystemGlobalMessage() for dialogs with conditions and actions
Note
Documentation generated by AI on 2026-03-04

◆ CreateGMSNotification()

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].

Parameters
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
Returns
(number|nil) The GMS notification handle, or nil on error
(boolean) Success flag - true if the notification was created successfully
(string) Status message from the GMS command response
See also
WrapperModule.CloseGMSNotification() for closing the notification by handle
WrapperModule.UpdateNotification() for updating the notification text
Note
Documentation generated by AI on 2026-03-04

◆ CreateInput()

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.

Parameters
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)
Returns
(number) The I/O handle returned by w.GetIoHandle()
See also
WrapperModule.CreateIO() for full parameter documentation
WrapperModule.CreateOutput() for creating output I/O points
Note
Documentation generated by AI on 2026-03-04

◆ CreateIO()

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.

Parameters
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:
  • permanent (boolean): If true, the I/O is recreated on startup
  • type (string|number): I/O type constant (e.g., 'IO_TYPE_OUTPUT' or mc.IO_TYPE_OUTPUT)
  • description (string): Human-readable description of the I/O point
Returns
(number) The I/O handle for the created or existing I/O point
Warning
Raises w.Error() if the plugin command fails
-- Create a temporary input (default device)
w.CreateIO(nil, 'ProbeSignal', true, nil)
-- Create a permanent output for a specific device
w.CreateIO('Spindle3', 'SpindleFwd', false, {permanent=true, description='Spindle forward'})
WrapperModule FunctionQueue Create()
Create a new FunctionQueue instance with the given name.
See also
WrapperModule.CreateInput() for input shortcut
WrapperModule.CreateOutput() for output shortcut
WrapperModule.RemoveIO() for removing dynamic I/O points
Note
Documentation generated by AI on 2026-03-04

◆ CreateOEMGCodes()

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.

Parameters
GCodeRangeString(string) A range string specifying G-code numbers to register as OEM subs (e.g., "271-272")
See also
WrapperModule.InterpretRangeString() for range string format details
WrapperModule._CreateOEMGCodes() for the actual implementation
Note
Documentation generated by AI on 2026-03-04

◆ CreateOrOpenFile()

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.

Parameters
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++
Warning
This function raises errors via w.Error() if the file cannot be opened for writing or if no editor can be located
See also
WrapperModule.FindNotepadPP() for automatic editor detection
WrapperModule.NPPEditor() and WrapperModule.GCEditEditor() for editor factory functions
Note
Documentation generated by AI on 2026-03-04

◆ CreateOrOpenSubroutine()

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.

Parameters
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
See also
WrapperModule.CreateOrOpenFile() for the underlying file creation and editor launch
WrapperModule.FindNotepadPP() for the editor detection logic
Note
Documentation generated by AI on 2026-03-04

◆ CreateOutput()

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.

Parameters
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)
Returns
(number) The I/O handle returned by w.GetIoHandle()
See also
WrapperModule.CreateIO() for full parameter documentation
WrapperModule.CreateInput() for creating input I/O points
Note
Documentation generated by AI on 2026-03-04

◆ CreateRegister()

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.

Parameters
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:
  • permanent (boolean): If true, the register is recreated on startup
  • type (string|number): Register type constant (e.g., 'REG_TYPE_OUTPUT' or mc.REG_TYPE_OUTPUT)
  • description (string): Human-readable description of the register
Returns
(number) The register handle for the created or existing register
Warning
Raises w.Error() if the plugin command fails
-- Create a temporary general register (default device)
w.CreateRegister('ScreenState')
-- Create a permanent numeric output register with description
w.CreateRegister('MachMotion', 'DriftAmount', {permanent=true, type=mc.REG_TYPE_NUMERIC_OUTPUT, description='amount drifted from last home'})
See also
WrapperModule.RemoveRegister() for removing dynamic registers
WrapperModule.CreateIO() for creating dynamic I/O points
Note
Documentation generated by AI on 2026-03-04

◆ CreateSimpleCommand()

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()).

Parameters
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
See also
WrapperModule.CreateCommand() for registering the command in m.Commands
WrapperModule.CreateSimpleUserCommand() for creating a persistent user command
Note
Documentation generated by AI on 2026-03-04

◆ CreateSimpleUserCommand()

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.

Parameters
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
See also
WrapperModule.SaveUserCommand() for persisting the command to disk
WrapperModule.CreateCommand() for registering the command in m.Commands
WrapperModule.CreateSimpleCommand() for a non-persistent pre-canned command variant
Note
Documentation generated by AI on 2026-03-04

◆ CreateSingleMessage()

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.

Parameters
Table(table) Legacy single-message configuration table with keys:
  • Class (string): Message class - "Alarm", "Warning", "Notice", or "Process"
  • Description (string|nil): Message title text
  • ExtraLines (table|nil): Array of extra content panel tables
  • Time (number|nil): Action delay in milliseconds
  • Device (string|nil): Signal device - "Output Signals" or "Input Signals", or an I/O device name
  • Signal (string|nil): Signal or I/O name for the trigger condition
  • Active (string|nil): Trigger level - "High" or "Low"
  • Action (string|nil): Action type string such as "Disable Software", "Feed Hold", "Execute Script", etc.
Returns
(string|nil) The GMS monitor handle, or nil on error
(boolean) Success flag - true if the monitor was created successfully
(string) Status message from the GMS command response
See also
WrapperModule.CreateSystemGlobalMessage() for the current replacement function
Note
Documentation generated by AI on 2026-03-04

◆ CreateSystemGlobalMessage()

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.

Parameters
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
Returns
(string|nil) The GMS monitor handle string on success, or nil on error
(boolean) Success flag - true if the monitor was created successfully
(string) "System Monitor Created" on success, or "System Monitor Failed" on error
See also
WrapperModule.CreateGMSDialog() for simple dialogs without conditions
WrapperModule.CreateSingleMessage() for single-execution monitors (deprecated)
Note
Documentation generated by AI on 2026-03-04

◆ CreateToolInfoFile()

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.

Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if the file was written successfully
(string) Status message from w.FunctionCompleted() or the error from w.WriteTextFile()
Warning
Displays a blocking message dialog before creating the file. Mach must be restarted after this operation
See also
WrapperModule.GetToolInfo() which calls this if TOOL_NAMES is uninitialized
WrapperModule.GetToolName() which calls this if TOOL_NAMES is uninitialized
Note
Documentation generated by AI on 2026-03-04

◆ CreateToolSetter()

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().

Parameters
name(string) The name of the tool setter to create or retrieve
Returns
(table) The tool setter configuration table (newly created or pre-existing) with keys:
  • SetterName (string): The tool setter name
  • SectionName (string): The INI profile section name (e.g., "ToolSetter0")
  • AutoSetter (boolean): Whether this is an auto setter (default: false)
  • FixturesOffsets (boolean): Whether fixture offsets apply (default: false)
  • ProbeInput (number): Probe input index (default: 0)
  • Height (number): Tool setter height (default: 1)
  • ZPosition (number): Tool setter Z position (default: 0)
  • DisableSoftlimits (boolean): Whether soft limits are disabled (default: false)
  • GoToPosition (string): GoTo position name before touchoff (default: "")
  • EndGoToPosition (string): GoTo position name after touchoff (default: "")
See also
WrapperModule.GetToolSetter() to retrieve an existing tool setter by name
WrapperModule.WriteToolSetter() for the underlying profile write operation
Note
Documentation generated by AI on 2026-03-04

References name().

◆ CreateUserCommandActionOption()

WrapperModule CreateUserCommandActionOption ( name ,
func  )

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".

Parameters
name(string) The name key under which to register the action function
func(function) The user action function to register
Note
Documentation generated by AI on 2026-03-04

References func(), and name().

◆ CreateUserCommandFeedbackOption()

WrapperModule CreateUserCommandFeedbackOption ( name ,
func  )

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".

Parameters
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
Note
Documentation generated by AI on 2026-03-04

References func(), and name().

◆ DecrementCommandFeedbackUsage()

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.

Parameters
feedback_name(string) The name of the command feedback whose usage counter is to be decremented
Note
Documentation generated by AI on 2026-03-04

◆ DecrementCommandUsage()

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.

Parameters
command_name(string) The name of the command whose usage counter is to be decremented
Note
Documentation generated by AI on 2026-03-04

◆ DecrementMCodeHoldCount()

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.

Returns
(number) The updated hold counter value after decrement (minimum 0)
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.IncrementMCodeHoldCount() for the inverse operation
WrapperModule.IsMCodeHoldActive() to check the current hold state
Note
Documentation generated by AI on 2026-03-04

◆ DeepCopy()

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.

Parameters
from(table) The source table to copy from
to(table|nil) The destination table to copy into. If nil, a new table is created
Returns
(table) The destination table with copied data
(boolean) Success flag - always true
(string) Status message - "Copied Tables"
Note
Documentation generated by AI on 2026-03-04

◆ deepcopy()

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.

Parameters
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
Returns
(any) A deep copy of orig with independent memory that does not reference the original
Warning
Only one argument should be supplied by callers. Passing the second argument can have unintended consequences as documented on the Lua-users wiki.
See also
http://lua-users.org/wiki/CopyTable for the original source
Note
Documentation generated by AI on 2026-03-04

◆ DeleteAllUserCommands()

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.

Warning
This permanently deletes all user command files. In-memory commands in m.Commands are not cleared
Note
Documentation generated by AI on 2026-03-04

◆ DeleteMachMotionLogFile()

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.

Warning
This permanently deletes the log file. This action cannot be undone
Note
Documentation generated by AI on 2026-03-04

◆ DirectoryExists()

WrapperModule DirectoryExists ( Path )

Check to see if a directory exists.

WrapperModule.DirectoryExists

Note
Documentation generated by AI on 2026-03-03

Check to see if a directory exists.

◆ DisableGMSMessage()

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.

Parameters
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
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.FullyDisableGMSMessage() for permanently disabling a message
WrapperModule.CloseGMSMessage() for closing a message entirely
Note
Documentation generated by AI on 2026-03-04

◆ DisableProbeOutput()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Note
Documentation generated by AI on 2026-03-04

◆ DistanceFunction()

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.

Parameters
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)
Returns
(number|nil) The Euclidean distance, or nil on error
(boolean) Success flag - true if the distance was computed successfully
(string) Status message describing the result or w.FunctionError() on failure
-- 2D distance between (0,0) and (3,4)
local dist, ok, msg = w.DistanceFunction(0, 3, 0, 4)
-- dist == 5.0
-- 1D distance
local dist, ok, msg = w.DistanceFunction(10, 20)
-- dist == 10.0
WrapperModule DistanceFunction(A1, A2, B1, B2, C1, C2)
Calculate the Euclidean distance between two points in up to three dimensions.
Note
Documentation generated by AI on 2026-03-04

◆ Distribute()

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.

Parameters
data(table) Input configuration table with keys:
  • count (number): The number of objects to distribute (required)
  • start (number): The starting position of the available space (required)
  • length (number): The total length of the available space (required)
  • constraints (table|nil): Optional constraints table with keys:
    • minimum_padding (number): Minimum space between objects. Default: 1
    • maximum_padding (number|nil): Maximum space between objects
    • maximum_size (number|nil): Maximum size to assign to each object
Returns
(table) An array of tables, one per object, each with keys:
  • start (number): The starting position of the object
  • end (number): The ending position of the object
  • length (number): The size of the object
-- Distribute 3 buttons across 100 pixels starting at position 5
local layout = w.Distribute({count=3, start=5, length=100,
constraints={minimum_padding=2, maximum_size=30}})
-- layout[1].start, layout[1].end, layout[1].length, etc.
GrinderCenterlessScreenV02 LayoutObjects layout()
Lay out all visible objects in the LayoutObjects grid.
WrapperModule Distribute(data)
Distribute a number of objects evenly across a one-dimensional space.
module start()
Start a new profiling session and begin instrumenting function calls.
Note
Documentation generated by AI on 2026-03-04

◆ DoesExistGoToPosition_MachineZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if at least one GoTo position is configured as a machine zero position, false otherwise
See also
WrapperModule.GetConfiguredGoToPosition_MachineZero() to retrieve the machine zero position configuration
WrapperModule.GetConfiguredGoToPositionGcode_MachineZero() to get G-code for the machine zero position
Note
Documentation generated by AI on 2026-03-04

◆ DoesExistGoToPosition_Park()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if at least one GoTo position is configured as a park position, false otherwise
See also
WrapperModule.GetConfiguredGoToPosition_Park() to retrieve the park position configuration
WrapperModule.GetConfiguredGoToPositionGcode_Park() to get G-code for the park position
Note
Documentation generated by AI on 2026-03-04

◆ DoesExistGoToPosition_PartZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if at least one GoTo position is configured as a part zero position, false otherwise
See also
WrapperModule.GetConfiguredGoToPosition_PartZero() to retrieve the part zero position configuration
WrapperModule.GetConfiguredGoToPositionGcode_PartZero() to get G-code for the part zero position
Note
Documentation generated by AI on 2026-03-04

◆ DoesExistGoToPosition_ToolChange()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if at least one GoTo position is configured as a tool change position, false otherwise
See also
WrapperModule.GetConfiguredGoToPosition_ToolChange() to retrieve the tool change position configuration
WrapperModule.GetConfiguredGoToPositionGcode_ToolChange() to get G-code for the tool change position
Note
Documentation generated by AI on 2026-03-04

◆ DoesExistGoToPosition_ToolSetter()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if at least one GoTo position is configured as a tool setter position, false otherwise
See also
WrapperModule.GetConfiguredGoToPosition_ToolSetter() to retrieve the tool setter position configuration
WrapperModule.GetConfiguredGoToPositionGcode_ToolSetter() to get G-code for the tool setter position
Note
Documentation generated by AI on 2026-03-04

◆ DoesOEMParamExist()

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.

Parameters
RegName(string) The name of the OEM parameter register to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the OEM parameter register exists, false otherwise
See also
WrapperModule.GetOEMParamValue() for reading the register value
Note
Documentation generated by AI on 2026-03-04

◆ DoesParameterExist()

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.

Parameters
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
Returns
(boolean) True if the parameter exists and the API call returned MERROR_NOERROR, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMParamSig()

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().

Parameters
SigName(string) The OEM parameter register name of the signal to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) The current signal or I/O state
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMParamValue()

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().

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The numeric value of the register
See also
WrapperModule.GetOEMParamValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMParamValueCached()

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().

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The cached numeric value of the register
See also
WrapperModule.GetOEMParamValueCached() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMParamValueString()

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().

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The string value of the register
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMParamValueStringCached()

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().

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The cached string value of the register
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMRegValue()

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().

Parameters
RegName(string) The name of the OEM register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The numeric value of the register
See also
WrapperModule.GetOEMRegValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eGetOEMRegValueString()

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().

Parameters
RegName(string) The name of the OEM register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The string value of the register
Note
Documentation generated by AI on 2026-03-04

◆ eGetParamSig()

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().

Parameters
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
Returns
(boolean) The current signal or I/O state
Note
Documentation generated by AI on 2026-03-04

◆ eGetRegValue()

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().

Parameters
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
Returns
(number) The numeric value of the register
See also
WrapperModule.GetRegValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eGetSignalState()

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().

Parameters
name(number) The signal ID to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) The current signal state as a boolean
See also
WrapperModule.GetSignalState() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

References name().

◆ eIsSignalMapped()

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().

Parameters
Signal(number) The signal ID to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the signal is mapped, false otherwise
See also
WrapperModule.IsSignalMapped() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eIsSignalMappedAndEnabled()

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().

Parameters
Signal(number) The signal ID to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the signal is both mapped and enabled, false otherwise
See also
WrapperModule.IsSignalMappedAndEnabled() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ ElapsedTime()

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.

Parameters
from_ll(userdata) The starting wxLongLong timestamp (from wx.wxGetLocalTimeMillis())
to_ll(userdata|nil) The ending wxLongLong timestamp. If nil, uses the current time
Returns
(number) Elapsed time in milliseconds as a 32-bit integer value
Warning
There is evidence that wx.wxGetLocalTimeMillis() can cause crashes. Consider using wxStopWatch() instead for measuring elapsed time.
local started = wx.wxGetLocalTimeMillis()
-- ... do work ...
local elapsed_ms = w.ElapsedTime(started)
Note
Documentation generated by AI on 2026-03-04

◆ EnableProbeOutput()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ EnumerateProfileSection()

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.

Parameters
section(string) The profile section name to enumerate
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) Table mapping key names (string) to their string values for the given profile section
Note
Documentation generated by AI on 2026-03-04

◆ eRegSendCommand()

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().

Parameters
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
Returns
(string) The response string from the register command
See also
WrapperModule.RegSendCommand() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ Error()

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.

Parameters
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
Warning
This function always raises an error and never returns. Use w.pcall() or xpcall() for protection
-- Raise a simple error
if not condition then
w.Error("Condition not met")
end
-- Raise with additional data
w.Error("Register read failed", {register = reg_name})
See also
WrapperModule.pcall() for protected function calls
WrapperModule.AlarmError() for GMS alarm delivery
WrapperModule.MCodeError() for M-code chunk errors
Note
Documentation generated by AI on 2026-03-04

◆ ErrorHandler()

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().

Parameters
err(any) The error value caught by xpcall
Returns
(table) A structured error object suitable for inspection with GetMessage(), GetTraceback(), etc.
See also
WrapperModule.pcall() for the wrapper that uses this handler
WrapperModule.Error() for the error object structure
Note
Documentation generated by AI on 2026-03-04

◆ ErrorMessage()

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.

Parameters
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
Returns
(string) A formatted human-readable error message string
See also
WrapperModule.Error() for the error object structure
WrapperModule.pcall() for protected calls that produce these error objects
Note
Documentation generated by AI on 2026-03-04

◆ EscapeCSV()

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.

Parameters
s(string) The string value to escape for CSV output
Returns
(string) The CSV-escaped string, quoted if necessary
Note
Documentation generated by AI on 2026-03-04

◆ eSetOEMParamSig()

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().

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ eSetOEMParamValue()

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().

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
See also
WrapperModule.SetOEMParamValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eSetOEMParamValueString()

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().

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValueString(), or nil on error
Note
Documentation generated by AI on 2026-03-04

◆ eSetOEMRegValue()

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().

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
See also
WrapperModule.SetOEMRegValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eSetParamSig()

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().

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ eSetRegValue()

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().

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
See also
WrapperModule.SetRegValue() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ eSetSignalState()

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().

Parameters
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
Returns
(number) The return code from mc.mcSignalSetState()
See also
WrapperModule.SetSignalState() for the non-error-raising variant
Note
Documentation generated by AI on 2026-03-04

References name().

◆ EvaluateLuaExpression()

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.

Returns
a table containing the result of the expression or some error information if the couldn't couldn't be evaluated

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'))")

Note
Documentation generated by AI on 2026-03-03

◆ eWaitForOEMParamSig()

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.

Parameters
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
Warning
This function raises errors via w.Error() instead of returning failure status. Callers must use pcall protection
This function blocks execution in M-code chunk context
See also
WrapperModule.WaitForOEMParamSig() for the non-error-raising equivalent
WrapperModule.WaitForSignal() for waiting on hardware signal state
Note
Documentation generated by AI on 2026-03-04

References AlarmMessage().

◆ Execute()

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.

Warning
Individual function errors are caught and logged but do not stop subsequent functions from executing
Note
Documentation generated by AI on 2026-03-04

◆ execute()

WrapperModule execute ( command ,
window_style ,
wait_on_return  )

◆ f()

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).

Parameters
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

◆ FileExists()

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.

Parameters
FileName(string) Full path to the file to check
Returns
(boolean|nil) True if the file exists and is readable, false if not found, nil if FileName is not a string
(boolean) Success flag - true if the check completed (even if file not found), false if FileName is not a string
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ FileRename()

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.

Parameters
old_name(string) The current full path of the file
new_name(string) The new full path to rename or move the file to
Returns
(boolean|nil) True if the rename succeeded, or nil on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ FileSizeBytes()

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.

Parameters
filepath(string) Full path to the file to measure
Returns
(number) File size in bytes
Warning
Raises a Lua error via w.Error() if the lfs (Lua File System) module is not loaded
See also
WrapperModule.FileSizeKilobytes() for the size in kilobytes
WrapperModule.FileSizeMegabytes() for the size in megabytes
Note
Documentation generated by AI on 2026-03-04

◆ FileSizeKilobytes()

WrapperModule FileSizeKilobytes ( filepath )

Get the size of a file in kilobytes.

Delegates to WrapperModule.FileSizeBytes() and divides the result by 1024.

Parameters
filepath(string) Full path to the file to measure
Returns
(number) File size in kilobytes
See also
WrapperModule.FileSizeBytes() for the raw byte size
WrapperModule.FileSizeMegabytes() for the size in megabytes
Note
Documentation generated by AI on 2026-03-04

◆ FileSizeMegabytes()

WrapperModule FileSizeMegabytes ( filepath )

Get the size of a file in megabytes.

Delegates to WrapperModule.FileSizeKilobytes() and divides the result by 1024.

Parameters
filepath(string) Full path to the file to measure
Returns
(number) File size in megabytes
See also
WrapperModule.FileSizeBytes() for the raw byte size
WrapperModule.FileSizeKilobytes() for the size in kilobytes
Note
Documentation generated by AI on 2026-03-04

◆ FilterProbePositions()

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.

Warning
This function always raises an error and should not be called
Note
Documentation generated by AI on 2026-03-04

◆ FindClosestPath()

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.

Parameters
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
Returns
(table|nil) Table with keys 'X', 'Y', 'Distance', 'Line' for the closest path point, or nil on error
(boolean) Success flag - true if closest path was found
(string) Status message describing the result
Warning
This function may take significant time for large G-code files as it scans every line
See also
WrapperModule.FindPath() for the per-line closest-point calculation
Note
Documentation generated by AI on 2026-03-04

◆ FindFile()

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"}.

Parameters
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
Returns
(string|nil) The full path to the found file, or nil if not found
Note
Documentation generated by AI on 2026-03-04

◆ FindNotepadPP()

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.

Parameters
skip_registry(boolean|nil) If true, skips the registry search and only checks standard directories
Returns
(string|nil) The full path to notepad++.exe, or nil if it cannot be found
See also
WrapperModule.NPPEditor() for creating a Notepad++ editor function from the found path
WrapperModule.CreateOrOpenFile() which calls this to locate an appropriate editor
Note
Documentation generated by AI on 2026-03-04

◆ FindPath()

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.

Parameters
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
Returns
(table|nil) Table with keys 'X', 'Y', 'Distance' describing the closest point, or nil on error
(boolean) Success flag - true if closest point was found
(string) Status message describing the result
See also
WrapperModule.FindClosestPath() which iterates all lines to find the globally closest path
Note
Documentation generated by AI on 2026-03-04

◆ FlushProfile()

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.

Note
Documentation generated by AI on 2026-03-04

◆ FromCSVToTable()

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.

Parameters
s(string) The CSV line string to parse (a single row of CSV data)
Returns
(table) Array of field value strings parsed from the CSV line
Note
Documentation generated by AI on 2026-03-04

◆ FromMultiLineCSVToTable()

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.

Parameters
s(string) The multi-line CSV string to parse
Returns
(table) Two-dimensional table where result[row] is an array of column values for that row
Note
Documentation generated by AI on 2026-03-04

◆ FullyDisableGMSMessage()

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.

Parameters
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
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.DisableGMSMessage() for temporarily disabling a message
WrapperModule.CloseGMSMessage() for closing a message entirely
Note
Documentation generated by AI on 2026-03-04

◆ func_name()

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.

Note
This entry documents the pattern/template usage; the specific inner function body varies by implementation
Documentation generated by AI on 2026-03-04

Referenced by GetInstance().

◆ FunctionButtonMDI()

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().

Parameters
Command(string) The MDI command string to execute after confirmation
inst(number|nil) The Mach4 instance handle. If nil, uses the selected instance
Returns
(nil) No meaningful primary return value on success
(boolean|nil) False if machine is not enabled; true (implicit) if idle guard triggered or user canceled
(string|nil) Status message from w.FunctionError() if machine is not enabled
Warning
Machine must be enabled. If machine is not idle, the command is silently skipped
See also
WrapperModule.MDICommand() for direct MDI execution without cycle start confirmation
WrapperModule.MDICommandNoDialog() for execution without any dialog
Note
Documentation generated by AI on 2026-03-04

◆ FunctionCompleted()

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.

Parameters
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
Returns
(string) Formatted log message string describing the completed function and context
Note
Documentation generated by AI on 2026-03-04

◆ FunctionError()

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.

Parameters
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
Returns
(string) The CustomMessage string, suitable for use as the third return value in error returns
Note
This function logs errors but does not raise them. Use w.Error() to raise exceptions
Documentation generated by AI on 2026-03-04

◆ GCEditEditor()

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.

Parameters
path_to_gceditexe(string) Full path to the GCEdit executable
Returns
(function) A function that accepts a file path string and returns a batch command string
See also
WrapperModule.CreateOrOpenFile() which accepts the returned function as the editor parameter
WrapperModule.NPPEditor() for the equivalent Notepad++ editor factory
Note
Documentation generated by AI on 2026-03-04

◆ GCodeCNTL1MSTToggle()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.GetGCodeCNTL1MST() to read the current state
WrapperModule.SetGCodeCNTL1MST() to explicitly enable the MST suppression bit
WrapperModule.ResetGCodeCNTL1MST() to explicitly disable the MST suppression bit
Note
Documentation generated by AI on 2026-03-04

◆ GcodeInterpGetPos()

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.

Parameters
InterpTool(number) The tool number for which to calculate the interpolated position
Returns
(table) A table with keys 'X' and 'Y' containing the adjusted interpolated positions
(boolean) Success flag - true if the calculation completed successfully
(string) Status message from w.FunctionCompleted()
Note
This function was created because mc.mcCntlGcodeInterpGetPos() does not include X/Y tool offsets
See also
mc.mcCntlGcodeInterpGetPos() in the Mach4 API documentation
Note
Documentation generated by AI on 2026-03-04

◆ GenericParabola()

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).

Parameters
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
Returns
(function) A function f(x) that returns the y value on the parabola for a given x
-- Create a parabola through three points
local f = w.geom.GenericParabola(0, 0, 10, 0, 5, 25)
local y = f(3) -- Calculate y at x=3
f(x)
Return a function that calculates y-values for a parabola passing through three given points.
See also
WrapperModule.geom.Parabola for a simplified version with assumed zero endpoints
Note
Documentation generated by AI on 2026-03-04

◆ GenericTextEntry()

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.

Parameters
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
Returns
(string) The value entered by the user, or an empty string if canceled
Note
Documentation generated by AI on 2026-03-04

◆ GetActiveCommands()

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.

Returns
(table) Table mapping command name (string) to a sub-table with keys: 'Value' (number) and 'Data' (table)
Note
Documentation generated by AI on 2026-03-04

◆ GetActiveFeedbacks()

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.

Returns
(table) Table mapping feedback name (string) to a sub-table with keys: 'Value' (number)
Note
Documentation generated by AI on 2026-03-04

◆ GetAlarmMessage() [1/2]

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.

Returns
(table) A GMS message table suitable for passing to w.CreateSystemGlobalMessage()
Note
This method is defined on the error object created by w.Error() and is called via err:GetAlarmMessage()
Documentation generated by AI on 2026-03-04

◆ GetAlarmMessage() [2/2]

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.

Parameters
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
Returns
(string) A formatted alarm message string suitable for display or GMS delivery
See also
WrapperModule.AlarmError() for delivering alarm messages
WrapperModule.Error() for the error object structure
Note
Documentation generated by AI on 2026-03-04

◆ GetAllActions()

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.

Returns
(table) Table mapping action name (string) to action function for all registered actions
Note
Documentation generated by AI on 2026-03-04

◆ GetAllAutoToolSetters()

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.

Returns
(table) A table keyed by tool setter name containing only auto tool setter configurations
(number) The count of auto tool setters
See also
WrapperModule.GetAllManualToolSetters() for the manual setter equivalent
WrapperModule.GetAllToolSetters() for all tool setters regardless of type
WrapperModule.IsAutoToolSetterEnabled() to check if any auto setters are configured
Note
Documentation generated by AI on 2026-03-04

◆ GetAllCommands()

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.

Returns
(table) Table mapping command name (string) to command configuration table for all registered commands
See also
WrapperModule.GetAllUserCommands() for loading user commands from disk
Note
Documentation generated by AI on 2026-03-04

◆ GetAllDevices()

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.

Parameters
filter(number|nil) Device type filter constant (e.g., mc.DEV_TYPE_IO, mc.DEV_TYPE_REG). If nil, returns all device types
Returns
(table) Table mapping device name (string) to device handle (number)
Note
Documentation generated by AI on 2026-03-04

References filter().

◆ GetAllFeedbacks()

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.

Returns
(table) Table mapping feedback name (string) to feedback function for all registered feedbacks
Note
Documentation generated by AI on 2026-03-04

◆ GetAllInputSignals()

WrapperModule GetAllInputSignals ( )

Retrieve all input signals registered in the current Mach4 instance.

Shortcut wrapper around w.GetAllSignals() that always retrieves input signals (input = true).

Returns
(table) Table mapping signal description (string) to signal ID number (number)
See also
WrapperModule.GetAllSignals() for full implementation details
WrapperModule.GetAllOutputSignals() for retrieving output signals
Note
Documentation generated by AI on 2026-03-04

◆ GetAllIOForDevice()

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.

Parameters
device_handle(number) The device handle whose I/O points are to be enumerated
Returns
(table) Table mapping I/O name (string) to I/O handle (number) for all I/O under the device
Note
Documentation generated by AI on 2026-03-04

◆ GetAllIOPaths()

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.

Returns
(table) Array of strings in the format "DeviceName/IOName" for every registered I/O point
Note
Documentation generated by AI on 2026-03-04

◆ GetAllManualToolSetters()

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.

Returns
(table) A table keyed by tool setter name containing only manual tool setter configurations
(number) The count of manual tool setters
See also
WrapperModule.GetAllAutoToolSetters() for the auto setter equivalent
WrapperModule.GetAllToolSetters() for all tool setters regardless of type
WrapperModule.IsManualToolSetterEnabled() to check if any manual setters are configured
Note
Documentation generated by AI on 2026-03-04

◆ GetAllOutputSignals()

WrapperModule GetAllOutputSignals ( )

Retrieve all output signals registered in the current Mach4 instance.

Shortcut wrapper around w.GetAllSignals() that always retrieves output signals (input = false).

Returns
(table) Table mapping signal description (string) to signal ID number (number)
See also
WrapperModule.GetAllSignals() for full implementation details
WrapperModule.GetAllInputSignals() for retrieving input signals
Note
Documentation generated by AI on 2026-03-04

◆ GetAllSignals()

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.

Parameters
input(boolean) If true, retrieves input signals; if false, retrieves output signals
Returns
(table) Table mapping signal description (string) to signal ID number (number)
Note
Documentation generated by AI on 2026-03-04

◆ GetAllToolSetters()

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.

Returns
(table) A table keyed by tool setter name, where each value is a configuration table with keys:
  • SetterName (string): The tool setter name
  • SectionName (string): The INI profile section name
  • AutoSetter (boolean): Whether this is an auto setter
  • ProbeInput (number): Probe input index
  • ProbeName (string): The G-code probe command name (e.g., "G31", "G31.1")
  • ProbeInputSignal (number): The Mach4 signal constant for the probe input
  • Height (number): Tool setter height
  • ZPosition (number): Tool setter Z position
  • DisableSoftlimits (boolean): Whether soft limits are disabled
  • GoToPosition (string): GoTo position name before touchoff
  • EndGoToPosition (string): GoTo position name after touchoff
(number) The count of tool setters found
See also
WrapperModule.WriteToolSetter() for the underlying profile write operation
WrapperModule.GetAllAutoToolSetters() to filter for auto setters only
WrapperModule.GetAllManualToolSetters() to filter for manual setters only
Note
Documentation generated by AI on 2026-03-04

◆ GetAllUserCommands()

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.

Returns
(table) Array of command configuration tables loaded from all user command INI files
See also
WrapperModule.GetUserCommandFolder() for the folder path
WrapperModule.ReadUserCommandFile() for per-file parsing
Note
Documentation generated by AI on 2026-03-04

◆ GetAnalogInput()

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.

Parameters
idx(number) The analog input channel index to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The current analog input value, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.GetAnalogOutput() for reading an analog output value
Note
Documentation generated by AI on 2026-03-04

◆ GetAnalogOutput()

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.

Parameters
idx(number) The analog output channel index to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The current analog output value, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetAnalogOutput() for writing an analog output value
WrapperModule.GetAnalogInput() for reading an analog input value
Note
Documentation generated by AI on 2026-03-04

◆ GetAppDataRoaming()

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.

Returns
(string) The path to the roaming AppData directory, or 'C:\Users\MachMotion\AppData\Roaming' as a last resort
See also
WrapperModule.GetAppDataRoaming_Method1() for the primary retrieval method
WrapperModule.GetAppDataRoaming_Method2() for the fallback retrieval method
Note
Documentation generated by AI on 2026-03-04

◆ GetAppDataRoaming_Method1()

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.

Returns
(string) The path to the roaming AppData directory (e.g., "C:\Users\Username\AppData\Roaming")
See also
WrapperModule.GetAppDataRoaming_Method2() for the environment variable fallback method
Note
Documentation generated by AI on 2026-03-04

◆ GetAppDataRoaming_Method2()

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.

Returns
(string) The path to the roaming AppData directory (e.g., "C:\Users\Username\AppData\Roaming")
See also
WrapperModule.GetAppDataRoaming_Method1() for the preferred Windows Shell API method
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisChildMotorID()

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.

Parameters
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
Returns
(table|nil) An array of motor ID numbers mapped to the axis, or nil if none are mapped
(boolean) Success flag - true if at least one motor is mapped, false otherwise
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetMotorParentAxisID() to find which axis a given motor is mapped to
WrapperModule.IsMotorMappedToAxis() to check if a specific motor is mapped to an axis
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisIsMoving()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS)
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the axis velocity magnitude is at or above the movement threshold
See also
WrapperModule.GetAxisIsMovingPositive() to check positive direction only
WrapperModule.GetAxisIsMovingNegative() to check negative direction only
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisIsMovingNegative()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS)
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the axis velocity is below the negative movement threshold
See also
WrapperModule.GetAxisIsMovingPositive() to check positive direction
WrapperModule.GetAxisIsNotMoving() to check for no motion
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisIsMovingPositive()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS)
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the axis velocity exceeds the positive movement threshold
See also
WrapperModule.GetAxisIsMovingNegative() to check negative direction
WrapperModule.GetAxisIsNotMoving() to check for no motion
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisIsNotMoving()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS)
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the axis velocity is within the stationary threshold, false if moving or axis is invalid
See also
WrapperModule.GetAxisIsMoving() for the inverse check
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisLetter()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.C_AXIS)
Returns
(string) The single-letter axis identifier ("X", "Y", "Z", "A", "B", "C"), or "" for unrecognized axes
See also
WrapperModule.GetAxisName() for a similar function that returns "OB(n)" for out-of-band axes
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisMachinePos()

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.

Parameters
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
Returns
(number) The machine-coordinate position of the axis in setup units
See also
WrapperModule.GetAxisPos() for part-coordinate position retrieval
WrapperModule.ConvertMachinePositionToPartPosition() to convert machine to part coordinates
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisName()

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.

Parameters
axis(number) The Mach4 axis ID constant (e.g., mc.X_AXIS, mc.A_AXIS)
Returns
(string) The axis name string: "X", "Y", "Z", "A", "B", "C", or "OB(n)" for out-of-band axes
See also
WrapperModule.GetAxisLetter() for a similar function that returns "" for out-of-band axes
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisPos()

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().

Parameters
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
Returns
(number) The part-coordinate position in current units (or degrees for rotary axes)
See also
WrapperModule.GetAxisMachinePos() for machine-coordinate position
WrapperModule.IsAxisRotary() to determine if an axis is rotary
WrapperModule.ConvertFromSetupUnits() for the unit conversion applied to linear axes
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisSoftMaxLimitFromProfile()

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.

Parameters
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
Returns
(number) The soft maximum limit for the axis in setup units
See also
WrapperModule.GetAxisSoftMinLimitFromProfile() for the minimum soft limit
WrapperModule.GetMotorSoftMaxLimitFromProfile() for the underlying motor soft limit read
Note
Documentation generated by AI on 2026-03-04

◆ GetAxisSoftMinLimitFromProfile()

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.

Parameters
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
Returns
(number) The soft minimum limit for the axis in setup units
See also
WrapperModule.GetAxisSoftMaxLimitFromProfile() for the maximum soft limit
WrapperModule.GetMotorSoftMinLimitFromProfile() for the underlying motor soft limit read
Note
Documentation generated by AI on 2026-03-04

◆ GetCache()

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.

Parameters
category(string) The cache category to read from
entry_name(string) The entry key to retrieve within the category
Returns
(any) The cached value, or nil if the entry does not exist
See also
WrapperModule.SetCache() for storing a value in the cache
WrapperModule.IsCached() for checking whether an entry exists
Note
Documentation generated by AI on 2026-03-04

◆ GetCachedIoHandle()

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.

Parameters
inst(number) The Mach4 instance handle (untagged, 0-5)
name(string) The full I/O path (e.g., "MachMotion/MyIO")
Returns
(number) The I/O handle
(number) The Mach4 error code (mc.MERROR_NOERROR on success)
See also
WrapperModule.GetIoHandle() for the higher-level wrapper
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCachedRegisterHandle()

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.

Parameters
inst(number) The Mach4 instance handle (untagged, 0-5)
name(string) The full register path (e.g., "MachMotion/MyRegister")
Returns
(number) The register handle
(number) The Mach4 error code (mc.MERROR_NOERROR on success)
See also
WrapperModule.GetRegHandle() for the higher-level wrapper
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCachedSignalHandle()

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.

Parameters
inst(number) The Mach4 instance handle (untagged, 0-5)
name(number) The signal ID whose handle is to be retrieved
Returns
(number) The signal handle
(number) The Mach4 error code (mc.MERROR_NOERROR on success)
See also
WrapperModule.GetSignalHandle() for the convenience wrapper
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCalculatedAutoToolSetterPosition()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No primary return value
(boolean) Success flag - true if the M901 MDI command executed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Raises a Lua error if no auto tool setter is configured
See also
WrapperModule.GetCalculatedManualToolSetterPosition() for the manual tool setter equivalent
WrapperModule.IsAutoToolSetterEnabled() to check whether an auto setter is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetCalculatedManualToolSetterPosition()

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).

Parameters
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
Returns
(number|nil) The calculated tool setter Z position, or nil on error
(boolean) Success flag - true if the calculation succeeded
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Raises a Lua error if no manual tool setter is configured
See also
WrapperModule.GetCalculatedAutoToolSetterPosition() for the auto tool setter equivalent
WrapperModule.GetToolSetterHeight() to retrieve the tool setter height by name
Note
Documentation generated by AI on 2026-03-04

◆ GetCallStack()

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.

Parameters
start_frame(number|nil) The starting stack frame index. If nil, defaults to 2 (immediate caller)
Returns
(string) Multi-line call stack string with one line per stack frame
See also
WrapperModule.debug.BriefParameterList() for parameter formatting
WrapperModule.debug.GetFunctionName() for name resolution
Note
Documentation generated by AI on 2026-03-04

◆ GetCarouselCumulativeRotation()

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.

Parameters
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
Returns
(number) The cumulative rotation in degrees (positive or negative, not bounded to 0-360)
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message including the cumulative degrees and number of rotations
Warning
Raises a Lua error via w.Error() if part_position is true and axis is an OB (auxiliary) axis
See also
WrapperModule.GetCarouselRotationWithLimits() which uses this value to select the best rotation path
Note
Documentation generated by AI on 2026-03-04

◆ GetCarouselRotationWithLimits()

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.

Parameters
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
Returns
(number) The absolute axis position to command (includes cumulative rotation history)
(boolean) Success flag - true if a viable path was found, false if no path is within limits
(string) Status message describing the chosen path or an error if no viable path exists
Warning
Raises a Lua error via w.Error() if part_position is true and axis is an OB (auxiliary) axis
Returns the current position with success=false if no viable path exists within ±(MAX_DEGREES - SAFETY_MARGIN)
See also
WrapperModule.IsCarouselPathViable() to check if a given movement stays within limits
WrapperModule.CalculateCarouselPathScore() for the path scoring algorithm
WrapperModule.GetCarouselCumulativeRotation() to read the current cumulative rotation
Note
Documentation generated by AI on 2026-03-04

◆ GetCommandDeviceName()

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.

Returns
(string) The Commands device name: "Commands"
See also
WrapperModule.GetCommandRegisterName() for building register names under this device
Note
Documentation generated by AI on 2026-03-04

◆ GetCommandFeedbackIOName()

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.

Parameters
name(string) The command feedback name to format
Returns
(string) The I/O name string in the format "[Feedback] <cleaned_name>"
See also
WrapperModule.GetCommandFeedbackRegisterName() for the underlying name format
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCommandFeedbackRegisterName()

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.

Parameters
name(string) The command feedback name to format
Returns
(string) The register name string in the format "[Feedback] <cleaned_name>"
See also
WrapperModule.GetCommandRegisterName() for the analogous command register name
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCommandFeedbackState()

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:

  • "Pre-Canned": calls the registered m.CommandFeedbacks function
  • "Input Signal" / "Output Signal": reads the signal state via mc.mcSignalGetState(), caching the handle
  • "I/O": reads the I/O state via mc.mcIoGetState(), caching the handle
  • "User Script": calls the registered user.UserCommandsFeedback function via w.pcall() Returns false if the source type is unrecognized or the source is not found.
    Parameters
    command_table(table) The command configuration table containing FeedbackSourceType, FeedbackSource, and related fields
    Returns
    (boolean) The current feedback state: true if active/on, false if inactive/off or not found
    Note
    Documentation generated by AI on 2026-03-04

◆ GetCommandIOName()

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.

Parameters
name(string) The command name to format
Returns
(string) The I/O name string in the format "[Command] <cleaned_name>"
See also
WrapperModule.GetCommandRegisterName() for the underlying name format
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetCommandRegisterName()

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.

Parameters
name(string) The command name to format
Returns
(string) The register name string in the format "[Command] <cleaned_name>"
See also
WrapperModule.GetCommandFeedbackRegisterName() for the analogous feedback register name
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetConfiguredGoToPosition_MachineZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The machine zero position configuration table if found, or an empty table if not configured
(boolean) True if the machine zero position was found, false otherwise
(string) Status message describing the result
See also
WrapperModule.DoesExistGoToPosition_MachineZero() to check existence without retrieving data
WrapperModule.GetConfiguredGoToPositionGcode_MachineZero() to get G-code for the machine zero position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPosition_Park()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The park position configuration table if found, or an empty table if not configured
(boolean) True if the park position was found, false otherwise
(string) Status message describing the result
See also
WrapperModule.DoesExistGoToPosition_Park() to check existence without retrieving data
WrapperModule.GetConfiguredGoToPositionGcode_Park() to get G-code for the park position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPosition_PartZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The part zero position configuration table if found, or an empty table if not configured
(boolean) True if the part zero position was found, false otherwise
(string) Status message describing the result
See also
WrapperModule.DoesExistGoToPosition_PartZero() to check existence without retrieving data
WrapperModule.GetConfiguredGoToPositionGcode_PartZero() to get G-code for the part zero position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPosition_ToolChange()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The tool change position configuration table if found, or an empty table if not configured
(boolean) True if the tool change position was found, false otherwise
(string) Status message describing the result
See also
WrapperModule.DoesExistGoToPosition_ToolChange() to check existence without retrieving data
WrapperModule.GetConfiguredGoToPositionGcode_ToolChange() to get G-code for the tool change position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPosition_ToolSetter()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The tool setter position configuration table if found, or an empty table if not configured
(boolean) True if the tool setter position was found, false otherwise
(string) Status message describing the result
See also
WrapperModule.DoesExistGoToPosition_ToolSetter() to check existence without retrieving data
WrapperModule.GetConfiguredGoToPositionGcode_ToolSetter() to get G-code for the tool setter position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionGcode_MachineZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The G-code string for the machine zero position move, or "" if not configured
(boolean) True if the machine zero position was found and G-code was generated, false otherwise
(string) Status message or error description
See also
WrapperModule.GetConfiguredGoToPosition_MachineZero() to retrieve the machine zero position configuration
WrapperModule.DoesExistGoToPosition_MachineZero() to check whether a machine zero position is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionGcode_Park()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The G-code string for the park position move, or "" if not configured
(boolean) True if the park position was found and G-code was generated, false otherwise
(string) Status message or error description
See also
WrapperModule.GetConfiguredGoToPosition_Park() to retrieve the park position configuration
WrapperModule.DoesExistGoToPosition_Park() to check whether a park position is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionGcode_PartZero()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The G-code string for the part zero position move, or "" if not configured
(boolean) True if the part zero position was found and G-code was generated, false otherwise
(string) Status message or error description
See also
WrapperModule.GetConfiguredGoToPosition_PartZero() to retrieve the part zero position configuration
WrapperModule.DoesExistGoToPosition_PartZero() to check whether a part zero position is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionGcode_ToolChange()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The G-code string for the tool change position move, or "" if not configured
(boolean) True if the tool change position was found and G-code was generated, false otherwise
(string) Status message or error description
See also
WrapperModule.GetConfiguredGoToPosition_ToolChange() to retrieve the tool change position configuration
WrapperModule.DoesExistGoToPosition_ToolChange() to check whether a tool change position is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionGcode_ToolSetter()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The G-code string for the tool setter position move, or "" if not configured
(boolean) True if the tool setter position was found and G-code was generated, false otherwise
(string) Status message or error description
See also
WrapperModule.GetConfiguredGoToPosition_ToolSetter() to retrieve the tool setter position configuration
WrapperModule.DoesExistGoToPosition_ToolSetter() to check whether a tool setter position is configured
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositionNames()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) An array of GoTo position name strings (e.g., {"ToolChange", "Park", "PartZero"})
See also
WrapperModule.GetConfiguredGoToPositions() to get the full configuration table for each position
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredGoToPositions()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) An array of GoTo position configuration tables
See also
WrapperModule.GetGoToPositionConfigurationFromIndex() for the per-position configuration format
WrapperModule.GetConfiguredGoToPositionNames() to get only the position names
Note
Documentation generated by AI on 2026-03-04

◆ GetConfiguredOperatorPanels()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) A table with the following structure:
  • [1..n] (table): Panel entries, each with keys 'ID', 'DeviceName', 'Enabled', 'PartNumber', 'Description', 'ProfileSection'
  • count (number): Total number of configured panels
  • PartNumbers (table): Set of configured part number strings (keys) for fast lookup
  • GetOperatorPanel (function): Accessor function(PartNumber) returning a matching panel or nil
See also
WrapperModule.GetOperatorPanelPartNumber() for the ID-to-info lookup used internally
WrapperModule.IsHardwareOperatorPanelEnabled() which uses this to detect hardware panels
Note
Documentation generated by AI on 2026-03-04

◆ GetControlConfiguration()

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.

Parameters
ModelArray(boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string
Returns
(string|table) The assembled model number string, or an array of model components if ModelArray is true
(boolean) Success flag - true if the model number was built successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetControlConfiguration_v1() for v1 schema details
WrapperModule.GetControlConfiguration_v2() for v2 schema details
Note
Documentation generated by AI on 2026-03-04

◆ GetControlConfiguration_v1()

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.

Parameters
ModelArray(boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string
Returns
(string|table) The assembled model number string, or an array of model components if ModelArray is true
(boolean) Success flag - true if the model number was built successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetControlConfiguration_v2() for the v2 schema variant
WrapperModule.GetControlConfiguration() which dispatches to v1 or v2 based on SCREEN_VERSION
Note
Documentation generated by AI on 2026-03-04

◆ GetControlConfiguration_v2()

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.

Parameters
ModelArray(boolean) If true, returns the model components as an ordered array; if false or nil, returns the assembled string
Returns
(string|table) The assembled model number string, or an array of model components if ModelArray is true
(boolean) Success flag - true if the model number was built successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetControlConfiguration_v1() for the v1 schema variant
WrapperModule.GetControlConfiguration() which dispatches to v1 or v2 based on SCREEN_VERSION
Note
Documentation generated by AI on 2026-03-04

◆ GetControlLicensedModules()

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.

Parameters
License(number) The license module bitmask constant to check (e.g., mc.MC_LIC_PRO, mc.MC_LIC_LITE)
Returns
(boolean) True if the specified license module bit is active, false otherwise
(boolean) Success flag - always true
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetControlLicensedVersion() which uses this to determine the software tier name
Note
Documentation generated by AI on 2026-03-04

◆ GetControlLicensedVersion()

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".

Returns
(string) The licensed version name: "MachPro", "Lite", "Educational", or "Demo"
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetControlLicensedModules() for the underlying license bit check
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrentFixtureIndex()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The current fixture index (1 for G54, 2 for G55, etc.; values > 6 for extended fixtures)
See also
WrapperModule.GetNearestRotation() for rotary axis positioning relative to fixture
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrentTool()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The current tool number, or 0/nil on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetCurrentTool() to update the current tool
WrapperModule.GetSelectedTool() for the tool staged for the next tool change
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrentToolPocket()

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.

Parameters
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
Returns
(number|nil) The current tool pocket number, or 0/nil on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetCurrentToolPocket() to update the current tool pocket
WrapperModule.GetSelectedToolPocket() for the staged (selected) pocket number
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrFileName()

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.

Parameters
caller_level(number|nil) The stack level to inspect. Defaults to 2 if not a number
Returns
(string) The short source file path of the resolved caller, or "(Unknown Script File)" if unavailable
See also
WrapperModule.GetCurrFnName() for the stack frame resolution logic
WrapperModule.GetCurrLineNo() for the corresponding line number lookup
WrapperModule.SrcLoc() to retrieve both file and line number together
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrFnName()

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.

Parameters
caller_level(number|nil) The starting stack level to inspect. Defaults to 2 if not a number
Returns
(string) The slash-delimited function name(s) of the resolved caller (e.g., "MyFunc" or "pcall/(unknown)")
(number) The actual stack level at which the function name was resolved
See also
WrapperModule.GetCurrFileName() which uses this function to locate the source file
WrapperModule.GetCurrLineNo() which uses this function to locate the line number
Note
Documentation generated by AI on 2026-03-04

◆ GetCurrLineNo()

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.

Parameters
caller_level(number|nil) The stack level to inspect. Defaults to 2 if not a number
Returns
(number) The current line number of the resolved caller, or 0 if unavailable
See also
WrapperModule.GetCurrFnName() for the stack frame resolution logic
WrapperModule.GetCurrFileName() for the corresponding file name lookup
WrapperModule.SrcLoc() to retrieve both file and line number together
Note
Documentation generated by AI on 2026-03-04

◆ GetCustomCntlDwellBarValue()

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.

Returns
(number) The current dwell bar value
See also
WrapperModule.SetCustomCntlDwellBarValue() to set the dwell bar value
WrapperModule.StartCustomCntlDwellBar() to start the dwell bar
WrapperModule.StopCustomCntlDwellBar() to stop the dwell bar
Note
Documentation generated by AI on 2026-03-04

◆ GetDefaultCommand()

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.

Parameters
name(string|nil) The command name. If nil, defaults to ""
Returns
(table) Default command table with keys: Name, Action, ActionOption, ActionOptionHandle, FeedbackSourceType, FeedbackTargetType, FeedbackSource, FeedbackSourceHandle, FeedbackCheckPeriod, FeedbackTarget, FeedbackTargetHandle
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetDefaultSpindle()

WrapperModule GetDefaultSpindle ( inst )

Get the default spindle number from the OEM parameters.

Reads the TC_DefaultSpindleNumber OEM parameter via w.eGetOEMParamValue() and returns it.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The default spindle number
See also
WrapperModule.GetSelectedSpindle() which falls back to this value if no spindle is selected
WrapperModule.SetSelectedSpindle() to update the selected spindle
Note
Documentation generated by AI on 2026-03-04

◆ GetDefaultUnitsModal()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) "G20" for imperial units, "G21" for metric units, or nil on error
(boolean) Success flag - true if the modal was determined successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetMachSetupUnits() for the underlying unit system read
WrapperModule.ConvertFromSetupUnits() to convert values between unit systems
Note
Documentation generated by AI on 2026-03-04

◆ GetDriveEnable()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) The current drive enable signal state, or false if not mapped, nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ GetFeatureKey()

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.

Parameters
feature(string) The feature name to look up (e.g., "MachMotion", "GMS", "Yaskawa")
Returns
(number|nil) The numeric feature key, or nil if the feature name is not recognized
Note
This function is deprecated. Use feature names from MachMotion/MachMotionLicensing/License.h directly
Documentation generated by AI on 2026-03-04

◆ GetFileQueueSleepTime()

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.

Returns
(number) The sleep time in milliseconds: 10
See also
WrapperModule.WaitForFileQueueResponse() for the polling loop that uses this value
Note
Documentation generated by AI on 2026-03-04

◆ GetFixtureSetterAutoName()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name of the currently selected auto fixture setter, or the auto tool setter selection if not set
See also
WrapperModule.SetFixtureSetterAutoName() to update the auto fixture setter selection
WrapperModule.GetToolSetterAutoName() for the equivalent tool setter function
Note
Documentation generated by AI on 2026-03-04

◆ GetFixtureSetterManualName()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name of the currently selected manual fixture setter, or the manual tool setter selection if not set
See also
WrapperModule.SetFixtureSetterManualName() to update the manual fixture setter selection
WrapperModule.GetToolSetterManualName() for the equivalent tool setter function
Note
Documentation generated by AI on 2026-03-04

◆ GetFunctionName()

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.

Parameters
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
Returns
(string|any) The function name string, or default if not cached
See also
WrapperModule.debug.UpdateFunctionNameMap() for populating the cache
Note
Documentation generated by AI on 2026-03-04

◆ GetG68PatchGcode()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) A G-code position string for all current axis positions, or "" if the patch is inactive
(boolean) False on profile read error, true otherwise (only returned on error)
(string) Error message from w.FunctionError() on profile read failure
See also
WrapperModule.GetGCodeToCurrentPosition() for the G-code generation logic
Note
Documentation generated by AI on 2026-03-04

◆ GetGCodeCNTL1MST()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if M/S/T waits are suppressed, false if waits are active
See also
WrapperModule.SetGCodeCNTL1MST() to set the MST suppression bit
WrapperModule.ResetGCodeCNTL1MST() to clear the MST suppression bit
WrapperModule.GCodeCNTL1MSTToggle() to toggle the bit
Note
Documentation generated by AI on 2026-03-04

◆ GetGCodeErrorDescription()

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.

Parameters
ErrorNumber(number) The G-code error number to look up (0-based index)
Returns
(string) Human-readable description of the G-code error
(boolean) Always true for the success flag
(string) Status message from w.FunctionCompleted()
Note
Documentation generated by AI on 2026-03-04

◆ GetGCodeToCurrentPosition()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) A G-code position string fragment with all enabled axis positions (e.g., " X1.0000 Y2.0000 Z-5.0000")
See also
WrapperModule.GetG68PatchGcode() for the G68 rotation compensation usage
WrapperModule.GetAxisLetter() for the axis letter lookup
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSAlarms()

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.

Returns
(boolean|nil) True if a GMS alarm is active, false if inactive, nil on error
(boolean) Success flag - true if the I/O state was read successfully
(string) Status message from w.FunctionError() on error, or " Ran Successfully" on success
See also
WrapperModule.GetGMSWarnings() for checking warnings only
WrapperModule.GetGMSAlarmsAndWarnings() for checking both alarms and warnings
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSAlarmsAndWarnings()

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.

Returns
(boolean|nil) True if any GMS alarm or warning is active, false if both are inactive, nil on error
(boolean) Success flag - true if both sub-calls completed successfully
(string) Status message from w.FunctionError() on error, or " Ran Successfully" on success
See also
WrapperModule.GetGMSWarnings() for checking warnings only
WrapperModule.GetGMSAlarms() for checking alarms only
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSClassName()

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.

Parameters
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"
Returns
(string) The display class name string: "Alarm", "Warning", "Notice", or "Process". Returns "Notice" as the default
See also
WrapperModule.GetGMSClassNumber() for converting class names to numeric codes
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSClassNumber()

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.

Parameters
class(number|string|nil) The class value to convert - either a numeric code or a string such as "Alarm", "Warning", "Notice", or "Process"
Returns
(number) The numeric class code (0=Alarm, 1=Warning, 2=Notice, 3=Process). Returns 2 (Notice) as the default
See also
WrapperModule.GetGMSClassName() for converting numeric codes to display name strings
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSHandleFromTitle()

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().

Parameters
title(string|nil) The title text to search for. If nil or not a string, returns an error
Returns
(string|nil) The GMS monitor handle string for the first matching message, or nil if not found
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.CloseGMSMessage() for closing a message by handle
WrapperModule.UpdateGMSClass() for updating a message's class by handle
Note
Documentation generated by AI on 2026-03-04

◆ GetGMSWarnings()

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.

Returns
(boolean|nil) True if a GMS warning is active, false if inactive, nil on error
(boolean) Success flag - true if the I/O state was read successfully
(string) Status message from w.FunctionError() on error, or " Ran Successfully" on success
See also
WrapperModule.GetGMSAlarms() for checking alarms only
WrapperModule.GetGMSAlarmsAndWarnings() for checking both alarms and warnings
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionConfigurationFromIndex()

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.

Parameters
idx(number) The zero-based index of the GoTo position to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table) The GoTo position configuration table for the specified index
See also
WrapperModule.GetGoToPositionConfigurationFromSection() for the configuration table structure
WrapperModule.GetConfiguredGoToPositions() to enumerate all configured positions
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionConfigurationFromName()

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.

Parameters
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
Returns
(table) The position configuration table if found, or an empty table if not found
(boolean) True if the position was found, false otherwise
(string|nil) nil on success, or "Position not found" error message
See also
WrapperModule.GetGoToPositionConfigurationFromIndex() for the configuration table structure
WrapperModule.GetConfiguredGoToPositions() to enumerate all configured positions
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionConfigurationFromSection()

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.

Parameters
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
Returns
(table) A configuration table with all position data. Key fields include:
  • Name (string): The position label
  • MachineCoord (boolean): True if the position uses machine coordinates (G53)
  • ToolChangePosition (boolean): True if this is the tool change position
  • MaxOrd (number): The highest configured movement order index
  • XPosition, YPosition, ... (number): Axis positions for each order step
  • XOrder, YOrder, ... (number): Axis movement orders for each step
See also
WrapperModule.GetGoToPositionConfigurationFromIndex() to read by position index
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionGcode()

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.

Parameters
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
Returns
(string|nil) The complete multi-line G-code block, or nil if the position was not found
(boolean) True if the position was found and G-code generated successfully
(string) Status message describing the result
See also
WrapperModule.GetGoToPositionGcodeFromName() for the underlying position lookup
WrapperModule.GetG68PatchGcode() for the G68 rotation patch logic
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionGcodeFromName()

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.

Parameters
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
Returns
(string) The G-code string for the named GoTo position, or "" if not found
See also
WrapperModule.GetGoToPositionGcodeFromTable() for the G-code generation logic
WrapperModule.GetConfiguredGoToPositions() to enumerate all configured positions
Note
Documentation generated by AI on 2026-03-04

◆ GetGoToPositionGcodeFromTable()

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.

Parameters
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
Returns
(string) The generated multi-line G-code string for the GoTo position move
Warning
Raises an error via w.Error() if MaxOrd is nil (no axis positions configured)
local pos_table = w.GetGoToPositionConfigurationFromName("ToolChange")
local gcode = w.GetGoToPositionGcodeFromTable(pos_table)
mc.mcCntlMdiExecute(inst, gcode)
See also
WrapperModule.GetGoToPositionConfigurationFromSection() to retrieve a position table
WrapperModule.GetGoToPositionGcodeFromName() to generate G-code directly from a name
Note
Documentation generated by AI on 2026-03-04

◆ GetHardwareEnable()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) The current hardware enable signal state, or false if not mapped, nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ GetInstanceCount()

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.

Returns
(number) The total number of active Mach4 instances
See also
WrapperModule.IsMultiInstance() for checking whether more than one instance is running
Note
Documentation generated by AI on 2026-03-04

◆ GetInstancesTable()

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:

  • nil: returns all instances (0 to mcCntlGetInstanceCount() - 1)
  • number: returns a single-element table containing that instance
  • table: returns a filtered subset containing only valid instance numbers (untagged, 0 to max)
  • string: returns a single-element table with the integer parsed from the string
  • other: returns a single-element table wrapping the value as-is
    Parameters
    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
    Returns
    (table) Array of valid Mach4 instance numbers
    Note
    Documentation generated by AI on 2026-03-04

◆ GetInstanceUnTaged()

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].

Parameters
inst(number|nil) The Mach4 instance handle to untag. If nil, uses current instance
Returns
(number) The untagged instance number in the range [0, 5]
See also
WrapperModule.GetUTI() for the shorthand alias
Note
Documentation generated by AI on 2026-03-04

◆ GetIoHandle()

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.

Parameters
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
Returns
(number) The I/O handle
(number) The Mach4 error code from mc.mcIoGetHandle()
Note
Documentation generated by AI on 2026-03-04

◆ GetIoState()

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.

Parameters
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
Returns
(boolean|nil) The current state of the I/O point as a boolean, or nil on error
(boolean) Success flag - true if the state was read successfully
(string) Status message describing the result
See also
WrapperModule.SetIoState() for setting the I/O state
Note
Documentation generated by AI on 2026-03-04

◆ GetJogMode()

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.

Returns
(number) The current jog mode (0=Continuous, 1=Incremental, 2=ABS, 3=Feedrate)
See also
WrapperModule.Jogger:SetJogModeContinuous() to set continuous mode
WrapperModule.Jogger:SetJogModeIncremental() to set incremental mode
WrapperModule.Jogger:SetJogModeABS() to set ABS mode
WrapperModule.Jogger:SetJogModeFeedrate() to set feedrate mode
Note
Documentation generated by AI on 2026-03-04

◆ GetKeysSortedByValue()

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).

Parameters
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
Returns
(table) An ordered array of keys from tbl, sorted by their associated values
-- Sort keys by ascending value
local t = {x=3, y=1, z=2}
local sorted = w.GetKeysSortedByValue(t)
-- sorted = {"y", "z", "x"} (values 1, 2, 3)
-- Sort keys by descending value
local sorted = w.GetKeysSortedByValue(t, function(a,b) return t[a] > t[b] end)
-- sorted = {"x", "z", "y"}
See also
https://stackoverflow.com/a/24565797/2092609
Note
Documentation generated by AI on 2026-03-04

References sortFunction().

◆ GetLastToolChangeStatus()

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.

Parameters
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
Returns
(boolean|nil) True if the last tool change was successful, false if it failed, nil on error
(boolean) Success flag - true if the status was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetToolChangeStatus() for reading individual tool change attributes
Note
Documentation generated by AI on 2026-03-04

◆ GetLocalVariable()

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.

Warning
This function will not work in compiled Lua modules where variable names are stripped by the compiler
Parameters
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
Returns
(any|nil) The value of the local variable, or nil if not found in that frame
Note
Documentation generated by AI on 2026-03-04

◆ GetMachBuild()

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.

Returns
(number) The Mach4 build number
Note
Documentation generated by AI on 2026-03-04

◆ GetMachineType()

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

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current selected instance
Returns
(table) A table with keys:
  • Description (string): Full mode description (e.g., "Lathe (Diameter)")
  • ControlMode (string): Simplified mode ("Mill", "Lathe", or "UnKnown")
  • ControlType (string): The global CONTROL_MACHINE_TYPE_STR value
local machine = w.GetMachineType()
if machine["ControlMode"] == "Lathe" then
-- handle lathe-specific logic
end
Note
Documentation generated by AI on 2026-03-04

◆ GetMachInfo()

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.

Returns
(string) Multi-line string with machine state, G-code file name, and optionally G-code line info
Note
This method is defined on the error object created by w.Error() and is called via err:GetMachInfo()
Documentation generated by AI on 2026-03-04

◆ GetMachSetupUnits()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The setup unit system: 200 for imperial, 210 for metric
Note
The result is cached; call w.ClearCache() if the profile has been changed at runtime
See also
WrapperModule.ConvertFromSetupUnits() to convert a value from setup units to another system
WrapperModule.GetDefaultUnitsModal() to get the corresponding G-code modal string
Note
Documentation generated by AI on 2026-03-04

◆ GetMaximumJogFeedrate()

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.

Parameters
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
Returns
(number) The maximum jog feedrate for the axis in setup units per minute
See also
WrapperModule.GetMinimumJogFeedrate() for the minimum jog feedrate
WrapperModule.GetMotorMaxVelocityFromProfile() for the underlying velocity read
Note
Documentation generated by AI on 2026-03-04

◆ GetMaxToolNumber()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The maximum tool number, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetPocketToolNumber() for pocket-to-tool lookup using this value
Note
Documentation generated by AI on 2026-03-04

◆ GetMaxToolPocketNumber()

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.

Parameters
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
Returns
(number) The maximum number of tool pockets configured
See also
WrapperModule.GetMaxToolNumber() for the maximum tool number
WrapperModule.GetCurrentToolPocket() for reading the current tool pocket
Note
Documentation generated by AI on 2026-03-04

◆ GetMCodeHoldCount()

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.

Returns
(number) The current MCode hold counter value
See also
WrapperModule.IncrementMCodeHoldCount() to request a hold
WrapperModule.DecrementMCodeHoldCount() to release a hold
Note
Documentation generated by AI on 2026-03-04

◆ GetmcSettingsDevice()

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.

Returns
(string) The string "core/settings"
Note
Documentation generated by AI on 2026-03-04

◆ GetMessage()

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.

Returns
(string) The error message string
Note
This method is defined on the error object created by w.Error() and is called via err:GetMessage()
Documentation generated by AI on 2026-03-04

◆ GetMinimumJogFeedrate()

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.

Parameters
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
Returns
(number) The minimum jog feedrate for the axis in setup units per minute
See also
WrapperModule.GetMaximumJogFeedrate() for the maximum jog feedrate
WrapperModule.GetMinimumJogRatePercentage() for the underlying percentage calculation
Note
Documentation generated by AI on 2026-03-04

◆ GetMinimumJogRatePercentage()

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.

Parameters
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
Returns
(number) The minimum jog rate percentage (at least 0.05) for the axis
See also
WrapperModule.GetMinimumJogFeedrate() to convert the percentage to a feedrate
WrapperModule.GetMotorCountsPerUnitFromProfile() for the encoder resolution value
Note
Documentation generated by AI on 2026-03-04

◆ GetMotionController()

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.

Returns
(string) The motion controller device name (e.g., "Sim0", "SimDev0", or a hardware device name)
See also
WrapperModule.IsSimMotionController() for checking if the device is a simulator
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorCountsPerUnitFromProfile()

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.

Parameters
MotorID(number) The motor ID whose counts-per-unit to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The counts-per-unit value for the specified motor
See also
WrapperModule.SetMotorCountsPerUnitFromProfile() to update the counts-per-unit value
WrapperModule.GetMotorMaxVelocityFromProfile() for a function that uses this value
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorMaxAccelFromProfile()

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.

Parameters
MotorID(number) The motor ID whose maximum acceleration to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The maximum acceleration in setup units per second squared
See also
WrapperModule.SetMotorMaxAccelFromProfile() to update the maximum acceleration
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorMaxVelocityFromProfile()

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.

Parameters
MotorID(number) The motor ID whose maximum velocity to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The maximum velocity in setup units per minute
See also
WrapperModule.SetMotorMaxVelocityFromProfile() to update the maximum velocity
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorParentAxisID()

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.

Parameters
MotorID(number) The motor ID to find the parent axis for
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The axis ID that MotorID is mapped to, or nil if not mapped
(boolean) Success flag - true if the motor was found on an axis
(string) Status message describing the result or w.FunctionError() if not found
See also
WrapperModule.GetAxisChildMotorID() to get all motors mapped to a given axis
WrapperModule.IsMotorMappedToAxis() to check if a specific motor-axis pairing exists
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorPositionInSetupUnits()

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.

Parameters
MotorID(number) The motor ID to query
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The current motor position in setup units (counts / counts-per-unit)
See also
WrapperModule.GetMotorCountsPerUnitFromProfile() to read counts-per-unit from the profile
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorSoftMaxLimitFromProfile()

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.

Parameters
MotorID(number) The motor ID whose soft maximum limit to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The soft maximum limit in setup units
See also
WrapperModule.SetMotorSoftMaxLimitFromProfile() to update the soft maximum limit
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ GetMotorSoftMinLimitFromProfile()

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.

Parameters
MotorID(number) The motor ID whose soft minimum limit to retrieve
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The soft minimum limit in setup units
See also
WrapperModule.SetMotorSoftMinLimitFromProfile() to update the soft minimum limit
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ GetMsg()

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.

Parameters
errorcode(number) The Mach4 error code to look up (e.g., mc.MERROR_NOERROR = 0)
Returns
(string) Formatted error message string, or "Unrecognized Mach Error Code: <code>" if not found
See also
WrapperModule.mcError.ErrorCodes for the full error code table
Note
Documentation generated by AI on 2026-03-04

◆ GetMsgCount()

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.

Returns
(number) The count of entries in the mcError.ErrorCodes table
See also
WrapperModule.mcError.ErrorCodes for the full error code table
Note
Documentation generated by AI on 2026-03-04

◆ GetNearestModValue()

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.

Parameters
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)
Returns
(number) The nearest value of the form (n * mod_value + offset) to the given value
See also
WrapperModule.GetNextModValue() to get the next boundary strictly above value
WrapperModule.GetPreviousModValue() to get the boundary at or below value
WrapperModule.GetNearestRotation() for rotary axis nearest-position calculation
Note
Documentation generated by AI on 2026-03-04

◆ GetNearestRotation()

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().

Parameters
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
Returns
(number) The absolute axis position to command to reach the nearest equivalent of the target angle
Warning
Raises a Lua error via w.Error() if part_position is true and axis is an OB (auxiliary) axis
See also
WrapperModule.GetNearestRotationFixedDirection() for forward-only rotation equivalent
WrapperModule.GetNearestModValue() for the underlying nearest boundary calculation
Note
Documentation generated by AI on 2026-03-04

◆ GetNearestRotationFixedDirection()

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().

Parameters
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
Returns
(number) The absolute axis position to command to reach the target angle in the forward direction
Warning
Raises a Lua error via w.Error() if part_position is true and axis is an OB (auxiliary) axis
See also
WrapperModule.GetNearestRotation() for the nearest-direction equivalent
WrapperModule.GetNextModValue() for the underlying next boundary calculation
Note
Documentation generated by AI on 2026-03-04

◆ GetNetworkAdapters()

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.

Returns
(table) Array of adapter tables, each with keys 'name' (string) and 'ip' (string)
(string|nil) Error message string if an error occurred, or nil on success
Note
Documentation generated by AI on 2026-03-04

◆ GetNextModValue()

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.

Parameters
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
Returns
(number) The smallest value of the form (n * mod_value + offset) that is > value
See also
WrapperModule.GetPreviousModValue() to get the boundary at or below value
WrapperModule.GetNearestModValue() to get the nearest boundary to value
Note
Documentation generated by AI on 2026-03-04

◆ GetNextUsefulStackFrame()

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.

Parameters
starting_frame(number) The stack frame index from which to begin searching
Returns
(number) The index of the next stack frame with a meaningful function name
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamDesc()

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.

Parameters
RegName(string) The name of the OEM parameter register to query
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) The description string of the register, or nil on error
(boolean) Success flag - true if the description was read successfully
(string) Status message describing the result
See also
WrapperModule.GetRegDesc() for reading descriptions of arbitrary registers
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamIOSigObject()

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.

Parameters
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
Returns
(table|nil) The parsed IOSig object table (see w.ParseIOSigPath() for schema), or nil on error or no selection
(boolean) Success flag - true if the object was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.GetParamIOSigObject() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamReg()

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.

Parameters
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
Returns
(number|nil) The current value of the register or analog signal, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamRegObject()

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.

Parameters
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
Returns
(table|nil) The parsed register object table, or nil on error or no selection
(boolean) Success flag - true if the object was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.GetParamRegObject() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamSig()

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.

Parameters
SigName(string) The OEM parameter register name of the signal to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) The current signal or I/O state, or nil on error
(boolean) Success flag - true if the state was read successfully
(string) Status message describing the result
See also
WrapperModule.GetParamSig() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValue()

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.

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The numeric value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMParamValue() for writing a numeric value
WrapperModule.eGetOEMParamValue() for the error-raising variant
WrapperModule.GetOEMParamValueCached() for a cached version
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValueBit()

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.

Parameters
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
Returns
(boolean|nil) The bit value as a boolean, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMParamValueBit() for setting a bit
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValueBool()

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).

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) The boolean value of the register, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMParamValueBool() for writing a boolean value
WrapperModule.ToBoolean() for the string-to-boolean conversion rules
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValueCached()

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.

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The numeric value of the register, or nil on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message describing the result
Note
This function caches results per instance to avoid repeated register reads
See also
WrapperModule.GetOEMParamValue() for the non-cached version
WrapperModule.eGetOEMParamValueCached() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValueString()

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.

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) The string value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMParamValueString() for writing a string value
WrapperModule.GetOEMParamValueStringCached() for a cached version
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMParamValueStringCached()

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.

Parameters
RegName(string) The name of the OEM parameter register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) The string value of the register, or nil on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message describing the result
Note
This function caches results per instance to avoid repeated register reads
See also
WrapperModule.GetOEMParamValueString() for the non-cached version
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMRegValue()

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.

Parameters
RegName(string) The name of the OEM register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The numeric value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMRegValue() for writing a numeric value
WrapperModule.eGetOEMRegValue() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMRegValueBit()

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.

Parameters
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
Returns
(boolean|nil) The bit value as a boolean, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMRegValueBit() for setting a bit
Note
Documentation generated by AI on 2026-03-04

◆ GetOEMRegValueString()

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.

Parameters
RegName(string) The name of the OEM register to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) The string value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetOEMRegValueString() for writing a string value
Note
Documentation generated by AI on 2026-03-04

◆ GetOperatorPanel()

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.

Parameters
PartNumber(string) The part number string to search for (e.g., "X15-10-01", "Software")
Returns
(table|nil) The panel data table with keys 'PartNumber', 'ID', 'DeviceName', 'Enabled', 'Description', 'ProfileSection', or nil if no panel with the given part number is found
See also
WrapperModule.GetConfiguredOperatorPanels() for the function that creates this accessor
Note
Documentation generated by AI on 2026-03-04

◆ GetOperatorPanelPartNumber()

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.

Parameters
id(number) The numeric operator panel ID to look up (e.g., 1 for X15-10-01, 24 for Software)
Returns
(table) A table with keys 'PartNumber' (string), 'Device' (string), and 'Description' (string), or an empty table if the ID is not recognized
See also
WrapperModule.GetConfiguredOperatorPanels() which uses this function to build the panel list
Note
Documentation generated by AI on 2026-03-04

◆ GetParameter()

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.

Parameters
param(number) The Mach4 control parameter number to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The current value of the specified control parameter
Note
Documentation generated by AI on 2026-03-04

◆ GetParameterBit()

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.

Parameters
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
Returns
(number) The bit value: 1 if the bit is set, 0 if clear
Note
Documentation generated by AI on 2026-03-04

◆ GetParameterBitCached()

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().

Parameters
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
Returns
(number) The bit value: 1 if the bit is set, 0 if clear
Note
Documentation generated by AI on 2026-03-04

◆ GetParameterCached()

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.

Parameters
param(number) The Mach4 control parameter number to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The current parameter value
Note
Documentation generated by AI on 2026-03-04

◆ GetParameterCacheName()

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.

Parameters
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
Returns
(string) The cache category name string in the format "MachParameter[<inst>]"
See also
WrapperModule.GetParameter() for reading parameters using this cache
Note
Documentation generated by AI on 2026-03-04

◆ GetParameters()

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.

Parameters
stack_frame(number) The stack frame to inspect, relative to the caller of this function
Returns
(table) Table mapping parameter name (string) to a sub-table with keys: 'pos' (number), 'value' (any), 'stringvalue' (string)
See also
WrapperModule.debug.BriefParameterList() for a formatted string version
Note
Documentation generated by AI on 2026-03-04

◆ GetParamIOSigObject()

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.

Parameters
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
Returns
(table|nil) The parsed IOSig object table (see w.ParseIOSigPath() for schema), or nil on error or no selection
(boolean) Success flag - true if the object was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.ParseIOSigPath() for the IOSig object schema
Note
Documentation generated by AI on 2026-03-04

◆ GetParamRegObject()

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.

Parameters
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
Returns
(table|nil) The parsed IOSig/register object table, or nil on error or no selection
(boolean) Success flag - true if the object was retrieved successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ GetParamSig()

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:

  • Output or input signal: calls w.GetSignalState()
  • I/O point: calls w.GetIoState() Returns an error if the IOSig object cannot be retrieved or the state read fails.
    Parameters
    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
    Returns
    (boolean|nil) The current signal or I/O state, or nil on error
    (boolean) Success flag - true if the state was read successfully
    (string) Status message describing the result
    Note
    Documentation generated by AI on 2026-03-04

◆ GetPocketToolNumber()

WrapperModule GetPocketToolNumber ( Pocket ,
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.

Parameters
Pocket(number) The pocket number to search for (1-based)
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The tool number assigned to the pocket, 0 if empty, or nil on error
(boolean) Success flag - true if the search completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetMaxToolNumber() for the maximum tool number used in the search
WrapperModule.GetCurrentToolPocket() to get the pocket of the currently loaded tool
Note
Documentation generated by AI on 2026-03-04

◆ GetPreCannedActionNames()

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.

Returns
(table) Array of pre-canned action name strings registered in m.CommandActions
Note
Documentation generated by AI on 2026-03-04

◆ GetPreCannedFeedbackNames()

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.

Returns
(table) Array of pre-canned feedback name strings registered in m.CommandFeedbacks
Note
Documentation generated by AI on 2026-03-04

◆ GetPreviousModValue()

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.

Parameters
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
Returns
(number) The largest value of the form (n * mod_value + offset) that is <= value
See also
WrapperModule.GetNextModValue() to get the next interval boundary above value
WrapperModule.GetNearestModValue() to get the nearest interval boundary to value
Note
Documentation generated by AI on 2026-03-04

◆ GetPreviousTool()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The previous tool number, or 0 on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetPreviousTool() to store the previous tool number
WrapperModule.GetCurrentTool() for the currently active tool number
Note
Documentation generated by AI on 2026-03-04

◆ GetPreviousToolPocket()

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.

Parameters
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
Returns
(number|nil) The previous tool pocket number, or 0 on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetPreviousToolPocket() to store the previous tool pocket number
WrapperModule.GetCurrentToolPocket() to get the currently active tool pocket
Note
Documentation generated by AI on 2026-03-04

◆ GetProbeFeedbackPositions()

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.

Parameters
positionnumber(number) The position slot index to read (0 through 5 inclusive)
Returns
(number) The stored probe feedback position value
Warning
Raises a Lua error if the position was never set or if the OEM parameter read fails
See also
WrapperModule.SetProbeFeedbackPositions() to store a probe feedback position
WrapperModule.ClearProbeFeedbackPositions() to reset all probe feedback positions
Note
Documentation generated by AI on 2026-03-04

◆ GetProgrammedFeedRate()

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.

Returns
(number) The programmed feed rate in current units per minute
Note
Mach4 reports SV_FEEDRATE in setup units regardless of the active G20/G21 mode
See also
WrapperModule.TimeToMove() which uses this value to estimate travel time
WrapperModule.ConvertUnits() for the unit conversion used when setup and current units differ
Note
Documentation generated by AI on 2026-03-04

◆ GetRecentMachDir()

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.

Returns
(string) The most recently used Mach4 directory path, or 'C:\Mach' on error
See also
WrapperModule.GetAppDataRoaming() for AppData directory resolution
Note
Documentation generated by AI on 2026-03-04

◆ GetRegDesc()

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.

Parameters
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
Returns
(string|nil) The description string of the register, or nil on error
(boolean) Success flag - true if the description was read successfully
(string) Status message describing the result
See also
WrapperModule.GetOEMParamDesc() for reading OEM parameter register descriptions
Note
Documentation generated by AI on 2026-03-04

◆ GetRegHandle()

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.

Parameters
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
Returns
(number) The register handle
(number) The Mach4 error code from mc.mcRegGetHandle()
Note
Documentation generated by AI on 2026-03-04

◆ GetRegValue()

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.

Parameters
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
Returns
(number|nil) The numeric value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetRegValue() for writing a numeric value
WrapperModule.eGetRegValue() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ GetRegValueLong()

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.

Parameters
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
Returns
(number|nil) The long integer value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetRegValueLong() for writing a long integer value
WrapperModule.GetRegValue() for reading a floating-point register value
Note
Documentation generated by AI on 2026-03-04

◆ GetRegValueString()

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.

Parameters
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
Returns
(string|nil) The string value of the register, or nil on error
(boolean) Success flag - true if the value was read successfully
(string) Status message describing the result
See also
WrapperModule.SetRegValueString() for writing a string value
Note
Documentation generated by AI on 2026-03-04

◆ GetReloadCounter()

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.

Returns
(number|nil) The current reload counter value, or nil on error
(boolean) Success flag - true if the register was read successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.IncrementReloadCounter() for incrementing the counter
Note
Documentation generated by AI on 2026-03-04

◆ GetRotatedPartPos()

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.

Parameters
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
Returns
(table) Table with keys 'X' and 'Y' containing the rotated coordinates
(boolean) Success flag - true if rotation was applied, false if rotation angle retrieval failed
(string) Status message describing the result
See also
WrapperModule.GetRotatedPosition() for a simpler forward rotation wrapper
WrapperModule.RotateAroundPoint() for the underlying rotation math
Note
Documentation generated by AI on 2026-03-04

◆ GetRotatedPosition()

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).

Parameters
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
Returns
(number) Rotated X coordinate
(number) Rotated Y coordinate
(boolean|nil) Success flag - false on error retrieving angle
(string|nil) Error message if angle retrieval failed
-- Rotate position with explicit angle
local x_rot, y_rot = w.GetRotatedPosition(10, 20, 45)
-- Use current G68 rotation
local x_rot, y_rot, success, msg = w.GetRotatedPosition(10, 20)
if success == false then
w.LogError(msg)
end
GCACaller Rotate(degree, shift)
Rotate the currently loaded G-code file by a specified degree and reload it.
See also
w.GetUnrotatedPosition() for reverse transformation
w.RotateAroundPoint() for the underlying rotation implementation
Note
Documentation generated by AI on 2026-03-03
See also
w.RotateAroundPoint() for the underlying rotation implementation

◆ GetSelectedInstance()

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.

Returns
(number) The currently selected Mach4 instance number
See also
WrapperModule.UpdateSelectedInstance() for forcing a cache refresh
WrapperModule.SetSelectedInstance() for changing the selected instance
Note
Documentation generated by AI on 2026-03-04

◆ GetSelectedSpindle()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The currently selected spindle number (at least 1)
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.SetSelectedSpindle() to update the selected spindle
WrapperModule.GetDefaultSpindle() for the default spindle number
Note
Documentation generated by AI on 2026-03-04

◆ GetSelectedTool()

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().

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The selected tool number, or 0/nil on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetSelectedTool() to update the selected tool number
WrapperModule.GetCurrentTool() to get the tool currently in the spindle
Note
Documentation generated by AI on 2026-03-04

◆ GetSelectedToolPocket()

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.

Parameters
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
Returns
(number|nil) The pocket number of the selected tool, or 0 on error/no selection
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.GetCurrentToolPocket() for the pocket of the currently loaded tool
WrapperModule.GetSelectedTool() for the selected tool number
Note
Documentation generated by AI on 2026-03-04

◆ GetSignalHandle()

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.

Parameters
inst(number) The Mach4 instance handle
signal_id(number) The signal ID whose handle is to be retrieved
Returns
(number) The signal handle
(number) The Mach4 error code
See also
WrapperModule.GetCachedSignalHandle() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ GetSignalInfo()

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.

Parameters
name(number) The signal ID to query
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table|nil) Table with keys: 'Enabled' (boolean), 'Name' (string), 'Description' (string), 'ActiveLow' (boolean), 'UserDescription' (string). Returns nil on error
(boolean) Success flag - true if the information was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.GetSignalState() for reading only the signal state
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetSignalNumber()

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.

Parameters
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
Returns
(number) The signal ID of the matching signal, or -1 if not found
(boolean) Success flag - true if a signal was found, false otherwise
(string) "Signal found" on success, or an error message on failure
Note
Documentation generated by AI on 2026-03-04

◆ GetSignalState()

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.

Parameters
name(number) The signal ID to read
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) The current signal state as a boolean, or nil on error
(boolean) Success flag - true if the state was read successfully
(string) Status message describing the result
See also
WrapperModule.eGetSignalState() for the error-raising variant
WrapperModule.SetSignalState() for setting the signal state
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetSignalUserDescription()

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.

Parameters
signal(number|string) The signal ID number or signal name string to look up
Returns
(string) The user-configured description if set, otherwise the system signal description
Note
Documentation generated by AI on 2026-03-04

◆ GetSoftLimits()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) True if soft limits are on, false if off, nil on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetSoftLimits() to enable or disable soft limits
Note
Documentation generated by AI on 2026-03-04

◆ GetTableCount()

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.

Parameters
T(table) The table whose entries are to be counted
Returns
(number) The total number of key-value pairs in the table
Note
Documentation generated by AI on 2026-03-04

◆ GetToleranceAmount()

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().

Parameters
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
Returns
(number) The tolerance amount in current units
See also
WrapperModule.ConvertFromImperialToCurrentUnits() for the unit conversion applied to the result
WrapperModule.IsAxisPositionInTolerancePart() which uses this value as a default tolerance
Note
Documentation generated by AI on 2026-03-04

◆ GetToolChangerData()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table|nil) A tool changer data table with the following structure, or nil on error:
  • Pocket (table): Pocket data keyed by pocket number, each with CSV header fields as keys
  • Parameters (table): OEM parameter values keyed by parameter name
  • GetPocket (function): Accessor function(self, pocket, key) returning a pocket field value
  • GetParam (function): Accessor function(self, key) returning an OEM parameter value
(boolean) Success flag - true if data was read successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.ReadCSV() for the CSV file reading function
Note
Documentation generated by AI on 2026-03-04

◆ GetToolChangerInstance()

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.

Returns
(number) The instance number to use for tool changer operations (0 or the selected instance)
See also
WrapperModule.UpdateToolChangerInstance() for forcing a cache refresh
Note
Documentation generated by AI on 2026-03-04

◆ GetToolChangerOverride()

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.

Parameters
tool_number(number) The tool number to check the override for
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) "Manual" if a manual override is active for the tool, "None" otherwise
See also
WrapperModule.IsToolChangerOverrideOn() to get a boolean result instead of a string
WrapperModule.GetToolTableUserValue() for the underlying tool table data access
Note
Documentation generated by AI on 2026-03-04

◆ GetToolChangeStatus()

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.

Parameters
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
Returns
(number|nil) The numeric attribute value, or 0 on error
(boolean) Success flag - true if the value was retrieved successfully
(string) Status message describing the result
See also
WrapperModule.SetToolChangeStatus() to set a tool change status attribute
Note
Documentation generated by AI on 2026-03-04

◆ GetToolInfo()

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.

Parameters
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")
Returns
(any|nil) The value of the requested attribute, or nil on error
(boolean) Success flag - true if the attribute was found
(string) Status message describing the result
See also
WrapperModule.GetToolName() to look up a tool name by tool number
WrapperModule.CreateToolInfoFile() which initializes the TOOL_NAMES table if missing
Note
Documentation generated by AI on 2026-03-04

◆ GetToolName()

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().

Parameters
Number(number|nil) The tool number to look up. If nil, uses the currently active tool
Returns
(string|nil) The tool name string, the number as a string if no range matches, or nil on error
(boolean) Success flag - true if the lookup completed (even if range not found)
(string) Status message describing the result
See also
WrapperModule.GetToolInfo() to retrieve a specific attribute for a named tool
WrapperModule.CreateToolInfoFile() which initializes the TOOL_NAMES table if missing
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetter()

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.

Parameters
name(string) The name of the tool setter to retrieve
Returns
(table|nil) The tool setter configuration table for the given name, or nil if not found
See also
WrapperModule.GetAllToolSetters() for the full collection of tool setters
WrapperModule.CreateToolSetter() to create a new tool setter entry
Note
Documentation generated by AI on 2026-03-04

References name().

◆ GetToolSetterAutoName()

WrapperModule GetToolSetterAutoName ( inst )

Get the currently selected auto tool setter name.

Reads the AutoSetterSelection OEM parameter string via w.eGetOEMParamValueString() and returns it.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name of the currently selected auto tool setter
See also
WrapperModule.SetToolSetterAutoName() to update the auto tool setter selection
WrapperModule.GetToolSetterManualName() for the manual tool setter equivalent
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterEndGoToPositionName()

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.

Parameters
ToolSetterName(string) The name of the tool setter whose end GoTo position to retrieve
Returns
(string) The name of the GoTo position to move to after touchoff, or "" if not configured
See also
WrapperModule.GetToolSetterGoToPositionName() to get the GoTo position before touchoff
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterFixtureOffsetMode()

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.

Parameters
ToolSetterName(string) The name of the tool setter whose fixture offset mode to retrieve
Returns
(number) The fixture offset mode value (default 0 if not configured)
See also
WrapperModule.GetToolSetterFixturesOffsets() to check if fixture offsets are enabled
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterFixturesOffsets()

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.

Parameters
ToolSetterName(string) The name of the tool setter to check
Returns
(boolean) True if fixture offsets are enabled for the tool setter, false otherwise
See also
WrapperModule.GetToolSetterFixtureOffsetMode() to get the fixture offset mode value
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterGoToPositionName()

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.

Parameters
ToolSetterName(string) The name of the tool setter whose GoTo position to retrieve
Returns
(string) The name of the GoTo position to move to before touchoff, or "" if not configured
See also
WrapperModule.GetToolSetterEndGoToPositionName() to get the GoTo position after touchoff
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterHeight()

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.

Parameters
ToolSetterName(string) The name of the tool setter whose height to retrieve
Returns
(number) The stored height of the tool setter, or 0 if not found
See also
WrapperModule.SetToolSetterHeight() to update the tool setter height
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterManualName()

WrapperModule GetToolSetterManualName ( inst )

Get the currently selected manual tool setter name.

Reads the ManualSetterSelection OEM parameter string via w.eGetOEMParamValueString() and returns it.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name of the currently selected manual tool setter
See also
WrapperModule.SetToolSetterManualName() to update the manual tool setter selection
WrapperModule.GetToolSetterAutoName() for the auto tool setter equivalent
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterPosition() [1/2]

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.

Parameters
ToolSetterName(string) The name of the tool setter whose Z position to retrieve
Returns
(number) The stored Z position of the tool setter
See also
WrapperModule.SetToolSetterPosition() to update the tool setter Z position
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterPosition() [2/2]

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.

Parameters
ToolSetterName(string) The name of the tool setter whose Z position to retrieve
Returns
(number) The stored Z position of the tool setter
See also
WrapperModule.SetToolSetterPosition() to update the tool setter Z position
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterProbeInput()

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).

Parameters
ToolSetterName(string) The name of the tool setter whose probe input index to retrieve
Returns
(number) The probe input index for the tool setter (0-3)
See also
WrapperModule.GetToolSetterProbeInputSignal() to get the Mach4 signal constant
WrapperModule.GetToolSetterProbeName() to get the G-code probe command name
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterProbeInputSignal()

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).

Parameters
ToolSetterName(string) The name of the tool setter whose probe input signal to retrieve
Returns
(number) The Mach4 signal constant for the probe input (e.g., mc.ISIG_PROBE)
See also
WrapperModule.GetToolSetterProbeInput() to get the numeric probe input index
WrapperModule.GetToolSetterProbeName() to get the G-code probe command name
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterProbeName()

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").

Parameters
ToolSetterName(string) The name of the tool setter whose probe name to retrieve
Returns
(string) The G-code probe command name for the tool setter's probe input
See also
WrapperModule.GetToolSetterProbeInput() to get the numeric probe input index
WrapperModule.GetToolSetterProbeInputSignal() to get the Mach4 signal constant
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterSoftlimitsEnabled()

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.

Parameters
ToolSetterName(string) The name of the tool setter to check
Returns
(boolean) True if soft limits are enabled for the tool setter, false if disabled
See also
WrapperModule.GetToolSetter() for the underlying configuration retrieval
Note
Documentation generated by AI on 2026-03-04

◆ GetToolSetterType()

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.

Parameters
ToolSetterName(string) The name of the tool setter whose type to retrieve
Returns
(string) "Auto" if the tool setter is automatic, "Manual" if it is manual
See also
WrapperModule.IsToolSetterAuto() for the underlying boolean check
WrapperModule.GetAllAutoToolSetters() to retrieve all auto setters
WrapperModule.GetAllManualToolSetters() to retrieve all manual setters
Note
Documentation generated by AI on 2026-03-04

◆ GetToolTableFileName()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The full path to the tool table file (e.g., "C:\Mach\Profiles\MyProfile\ToolTables\tooltable.tls")
Note
Documentation generated by AI on 2026-03-04

◆ GetToolTableUserValue()

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).

Parameters
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
Returns
(number) The numeric value of the user field, or 0 if tool number is 0
(boolean) Success flag - true if operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetToolTableUserValue() to write a numeric user field value
WrapperModule.GetToolTableUserValueString() to read a string user field value
Note
Documentation generated by AI on 2026-03-04

◆ GetToolTableUserValueString()

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).

Parameters
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
Returns
(string|number) The string value of the user field, or 0 if tool number is 0
(boolean) Success flag - true if operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetToolTableUserValueString() to write a string user field value
WrapperModule.GetToolTableUserValue() to read a numeric user field value
Note
Documentation generated by AI on 2026-03-04

◆ GetTraceback()

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.

Returns
(string) Multi-line traceback string with one line per stack frame
Note
This method is defined on the error object created by w.Error() and is called via err:GetTraceback()
Documentation generated by AI on 2026-03-04

◆ GetUnrotatedPosition()

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.

Parameters
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
Returns
(number) Unrotated X coordinate
(number) Unrotated Y coordinate
(boolean|nil) Success flag - false on error retrieving angle
(string|nil) Error message if angle retrieval failed
Note
This rotates in the -angle direction to reverse the original rotation
-- Unrotate position with explicit angle
local x_orig, y_orig = w.GetUnrotatedPosition(14.14, 14.14, 45)
-- Use current G68 rotation for unrotation
local x_orig, y_orig, success, msg = w.GetUnrotatedPosition(x_rot, y_rot)
See also
w.GetRotatedPosition() for forward transformation
w.RotateAroundPoint() for the underlying rotation implementation
Note
Documentation generated by AI on 2026-03-03
See also
w.RotateAroundPoint() for the underlying rotation implementation

◆ GetUserCommand()

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.

Parameters
command_name(string) The name of the user command to look up
Returns
(table) The command configuration table if found, or an empty table if not found
See also
WrapperModule.GetAllUserCommands() for loading all user commands
Note
Documentation generated by AI on 2026-03-04

◆ GetUserCommandFilename()

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

Parameters
command_name(string) The name of the user command
Returns
(string) Full path to the user command INI file
See also
WrapperModule.GetUserCommandFolder() for the folder path
Note
Documentation generated by AI on 2026-03-04

◆ GetUserCommandFolder()

WrapperModule GetUserCommandFolder ( )

Return the folder path where user command INI files are stored.

Constructs the path as: <MACH_DIRECTORY>\Profiles<MACH_PROFILE_NAME>\UserCommands

Returns
(string) Full path to the user commands folder
See also
WrapperModule.GetUserCommandFilename() for individual command file paths
Note
Documentation generated by AI on 2026-03-04

◆ GetUTI()

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.

Parameters
inst(number) The Mach4 instance handle (may be tagged). If not provided, uses current instance
Returns
(number) The untagged instance number in the range [0, 5]
See also
WrapperModule.GetInstanceUnTaged() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ GetValueBit()

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).

Parameters
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))
Returns
(boolean|nil) The bit value as a boolean (true if set, false if clear), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SetValueBit() for setting a bit
Note
Documentation generated by AI on 2026-03-04

◆ GetVersionInfo() [1/2]

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.

Returns
(string) Always returns an empty string
Note
This method is defined on the error object created by w.Error() and is called via err:GetVersionInfo()
Documentation generated by AI on 2026-03-04

◆ GetVersionInfo() [2/2]

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.

Parameters
component(string) The version component to retrieve. One of: 'core_build', 'core_build_str', 'revision', 'revision_str', 'branch', 'version'
Returns
(number|string|nil) The requested version component value, or nil if unrecognized
See also
WrapperModule.LoadVersionInfo() which must be called before this function to populate the table
Note
Documentation generated by AI on 2026-03-04

◆ HandlerA()

HandlerA ( ...)

◆ HasModal()

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.

Parameters
Line(string) The G-code line string to search
Modal(string) The modal code to search for (e.g., "G0", "G43.1", "M3")
Returns
(boolean|nil) True if the modal was found, false if not found, nil on invalid arguments
(boolean) Success flag - true if the check completed, false on invalid arguments
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ IncrementCommandFeedbackUsage()

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.

Parameters
feedback_name(string) The name of the command feedback whose usage counter is to be incremented
Note
Documentation generated by AI on 2026-03-04

◆ IncrementCommandUsage()

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.

Parameters
command_name(string) The name of the command whose usage counter is to be incremented
Note
Documentation generated by AI on 2026-03-04

◆ IncrementMCodeHoldCount()

WrapperModule IncrementMCodeHoldCount ( )

Increment the MCode hold counter by one.

Reads the current MCodeHoldCount OEM register value, adds one, then writes the updated value back.

Returns
(number) The updated hold counter value after increment
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.DecrementMCodeHoldCount() for the inverse operation
WrapperModule.IsMCodeHoldActive() to check the current hold state
Note
Documentation generated by AI on 2026-03-04

◆ IncrementReloadCounter()

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.

See also
WrapperModule.GetReloadCounter() for reading the current counter value
Note
Documentation generated by AI on 2026-03-04

◆ InhibitJogOnAllAxes()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.ReleaseInhibitJogOnAllAxes() to release the inhibit on all axes
WrapperModule.InhibitJogOnAxis() for per-axis inhibit control
Note
Documentation generated by AI on 2026-03-04

◆ InhibitJogOnAxis()

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.

Parameters
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
See also
WrapperModule.ReleaseInhibitJogOnAxis() to decrement the inhibit counter
WrapperModule.IsInhibitJogOnAxis() to check whether jogging is currently inhibited
Note
Documentation generated by AI on 2026-03-04

◆ InhibitJogOnCoordinatedAxes()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.ReleaseInhibitJogOnCoordinatedAxes() to release the inhibit
WrapperModule.InhibitJogOnAllAxes() to also inhibit OB (auxiliary) axes
Note
Documentation generated by AI on 2026-03-04

◆ InterpretRangeString()

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.

Parameters
range_string(string) The range string to parse (e.g., "1,3-5,8" or "36" or "4,10-12,18")
Returns
(table) A flat array of integers expanded from the range string
-- Single number
local t = w.InterpretRangeString("36") -- {36}
-- Comma list
local t = w.InterpretRangeString("1,2,4,8") -- {1,2,4,8}
-- Range
local t = w.InterpretRangeString("3-8") -- {3,4,5,6,7,8}
-- Mixed
local t = w.InterpretRangeString("4,10-12,18") -- {4,10,11,12,18}
Warning
Raises a Lua error() for malformed input: empty values, invalid numbers, or out-of-order ranges
Note
Documentation generated by AI on 2026-03-04

◆ IsAtGoToPositionFromName()

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.

Parameters
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
Returns
(boolean) True if all configured axes are within tolerance of the named position, false otherwise
Warning
Raises an error via w.Error() if the position has no configured axis movement entries
See also
WrapperModule.GetGoToPositionConfigurationFromName() to retrieve the position configuration
WrapperModule.VerifyAllAxesAreHomedCached() for the homing prerequisite check
Note
Documentation generated by AI on 2026-03-04

◆ IsAutoToolSetterEnabled()

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.

Returns
(boolean) True if at least one automatic tool setter is configured, false otherwise
See also
WrapperModule.GetAllAutoToolSetters() to retrieve the full list of auto tool setters
WrapperModule.IsManualToolSetterEnabled() for the manual setter equivalent
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisEnabled()

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.

Parameters
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
Returns
(boolean|nil) True if the axis is enabled, false if disabled, nil on error
(boolean) Success flag - true if the query completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetAxisChildMotorID() to check which motors are mapped to an axis
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisHomed()

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.

Parameters
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
Returns
(boolean|nil) True if the axis is homed or exempt, false if it is not homed, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message describing the result
See also
WrapperModule.VerifyAllAxesAreHomed() to check all axes at once
WrapperModule.MarkAxisAsHomedIfMotorsAreHomed() which is called when homed state is inconsistent
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisInSideSoftLimitsZone()

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].

Parameters
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
Returns
(boolean) True if the current axis position is within the soft limit zone or soft limits are disabled
See also
WrapperModule.IsAxisMachinePositionInSideSoftLimitsZone() to check an arbitrary position
WrapperModule.SetSoftLimits() to enable or disable soft limits
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisMachinePositionInSideSoftLimitsZone()

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].

Parameters
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
Returns
(boolean) True if position is within the soft limit zone or soft limits are disabled, false otherwise
See also
WrapperModule.IsAxisInSideSoftLimitsZone() to check the current axis position
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisPositionInToleranceMachine()

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.

Parameters
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
Returns
(boolean) True if the current machine position is within Tolerance of RequestedPosition, false otherwise
Warning
Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil
See also
WrapperModule.IsAxisPositionInToleranceMachineLastOutput() for the last output machine position check
WrapperModule.IsAxisPositionInTolerancePart() for part-coordinate position checking
WrapperModule.GetToleranceAmount() for the default tolerance value
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisPositionInToleranceMachineLastOutput()

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.

Parameters
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
Returns
(boolean) True if the last output machine position is within Tolerance of RequestedPosition, false otherwise
Warning
Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil
See also
WrapperModule.IsAxisPositionInToleranceMachine() for the current (not last output) machine position check
WrapperModule.GetToleranceAmount() for the default tolerance value
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisPositionInTolerancePart()

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.

Parameters
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
Returns
(boolean) True if the current part position is within Tolerance of RequestedPosition, false otherwise
Warning
Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil
See also
WrapperModule.IsAxisPositionInTolerancePartLastOutput() for the last output part position check
WrapperModule.IsAxisPositionInToleranceMachine() for machine-coordinate position checking
WrapperModule.GetToleranceAmount() for the default tolerance value
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisPositionInTolerancePartLastOutput()

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.

Parameters
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
Returns
(boolean) True if the last output part position is within Tolerance of RequestedPosition, false otherwise
Warning
Raises a Lua error via w.Error() if AxisID or RequestedPosition is nil
See also
WrapperModule.IsAxisPositionInTolerancePart() for the current (not last output) part position check
WrapperModule.GetToleranceAmount() for the default tolerance value
Note
Documentation generated by AI on 2026-03-04

◆ IsAxisRotary()

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.

Parameters
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
Returns
(boolean) True if the axis is a rotary (angular) axis, false if it is a linear axis
Note
Results are cached; call w.ClearCache() if the axis configuration has changed at runtime
See also
WrapperModule.GetAxisPos() which uses this to decide whether unit conversion is needed
Note
Documentation generated by AI on 2026-03-04

◆ IsCached()

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.

Parameters
category(string) The cache category to check
entry_name(string) The entry key to check within the category
Returns
(boolean) True if the entry exists (is non-nil) in the category, false otherwise
See also
WrapperModule.GetCache() for retrieving the cached value
WrapperModule.SetCache() for storing a value in the cache
Note
Documentation generated by AI on 2026-03-04

◆ IsCarouselPathViable()

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.

Parameters
current_cumulative_deg(number) The current cumulative rotation in degrees
movement_deg(number) The proposed movement in degrees (positive=CW, negative=CCW)
Returns
(boolean) True if the movement keeps the carousel within the rotation limits, false otherwise
(number) The resulting cumulative rotation in degrees after the movement
See also
WrapperModule.CalculateCarouselPathScore() to score a viable path
WrapperModule.GetCarouselRotationWithLimits() for the main carousel rotation function
Note
Documentation generated by AI on 2026-03-04

◆ IsCycleStartHoldActive()

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).

Returns
(boolean) True if a Cycle Start Hold is currently active, false otherwise
See also
WrapperModule.RequestCycleStartHold() to activate a hold
WrapperModule.ReleaseCycleStartHold() to release a hold
Note
Documentation generated by AI on 2026-03-04

◆ IsCycleStartPressedFlagSet()

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.

Returns
(boolean) True if the Cycle Start Pressed Flag is set, false otherwise
See also
WrapperModule.SetCycleStartPressedFlag() to set the flag
WrapperModule.ResetCycleStartPressedFlag() to clear the flag
Note
Documentation generated by AI on 2026-03-04

◆ IsDebugging()

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.

Parameters
inst(number) The Mach4 instance handle (currently unused; always uses current instance internally)
Returns
(boolean) True if debugging mode is active, false otherwise
Note
The result is cached after the first call; changing the OEM parameter at runtime will not affect the cached value
Documentation generated by AI on 2026-03-04

◆ IsEditorActive()

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.

Returns
(boolean) True if Mach is running in editor mode, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ IsFeatureLicensed()

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.

Parameters
feature_name(string|nil) The feature name to check (e.g., "MachMotion", "GMS"). If nil, returns false
Returns
(boolean) True if the feature is licensed, false otherwise
Note
This function is deprecated. Use w.CheckIfLicensed() for the updated 2025 license checker
See also
WrapperModule.CheckIfLicensed() for the updated license checker
Note
Documentation generated by AI on 2026-03-04

◆ IsGCodeFileLoaded()

WrapperModule IsGCodeFileLoaded ( inst )

Check whether a G-code file is currently loaded in the specified instance.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if a G-code file is loaded (filename is non-empty and non-nil), false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ IsGCodeFileLoadedInAnotherInstance()

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.

Parameters
filename(string) The full path to the G-code file to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the file is loaded in any instance, false if not found in any instance
(boolean) Success flag - always true
(string) Status message from w.FunctionCompleted(), or description of which instance has the file loaded
Note
Documentation generated by AI on 2026-03-04

◆ IsGeneralInput()

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.

Parameters
sig_id(number) The signal ID to check
Returns
(boolean) True if sig_id is a general input signal, false otherwise
See also
WrapperModule.IsGeneralOutput() for checking general output signals
WrapperModule.INPUTS for the general input signal ID table
Note
Documentation generated by AI on 2026-03-04

◆ IsGeneralOutput()

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.

Parameters
sig_id(number) The signal ID to check
Returns
(boolean) True if sig_id is a general output signal, false otherwise
See also
WrapperModule.IsGeneralInput() for checking general input signals
WrapperModule.OUTPUTS for the general output signal ID table
Note
Documentation generated by AI on 2026-03-04

◆ IsGMSLicensed()

WrapperModule IsGMSLicensed ( )

Check whether the GMS feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "GMS" feature.

Returns
(boolean) True if GMS is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsGrinderCCLicensed()

WrapperModule IsGrinderCCLicensed ( )

Check whether the GrinderCC feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "GrinderCC" feature.

Returns
(boolean) True if GrinderCC is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsHardwareOperatorPanelEnabled()

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".

Returns
(boolean) True if at least one hardware operator panel is configured, false otherwise
See also
WrapperModule.GetConfiguredOperatorPanels() for the full panel configuration list
Note
Documentation generated by AI on 2026-03-04

◆ IsHomeSwitchActive()

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.

Parameters
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
Returns
(boolean) True if a home switch is active, false if all are clear
(number|nil) The axis ID of the active home switch, or nil if none are active
(string) Status message indicating which axis home is active or that all are clear
See also
WrapperModule.IsLimitSwitchActive() for checking limit switches
Note
Documentation generated by AI on 2026-03-04

◆ IsInhibitJogOnAxis()

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.

Parameters
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
Returns
(boolean) True if jogging is inhibited for the axis, false if jogging is allowed
See also
WrapperModule.InhibitJogOnAxis() to inhibit jogging on an axis
WrapperModule.ReleaseInhibitJogOnAxis() to release a jog inhibit
Note
Documentation generated by AI on 2026-03-04

◆ IsJogging()

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.

Returns
(boolean) True if the axis is jogging or stopping, false if fully stopped
See also
WrapperModule.Jogger:Stop() to initiate a stop
WrapperModule.Jogger:Wait() to block until jogging is complete
Note
Documentation generated by AI on 2026-03-04

◆ IsJogModeABS()

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).

Returns
(boolean) True if the Jogger is in ABS mode, false otherwise
See also
WrapperModule.Jogger:SetJogModeABS() to activate ABS mode
Note
Documentation generated by AI on 2026-03-04

◆ IsJogModeContinuous()

WrapperModule Jogger IsJogModeContinuous ( )

Check whether this Jogger is in continuous jog mode.

Returns true if the current jog mode is 0 (Continuous mode).

Returns
(boolean) True if the Jogger is in continuous mode, false otherwise
See also
WrapperModule.Jogger:SetJogModeContinuous() to activate continuous mode
Note
Documentation generated by AI on 2026-03-04

◆ IsJogModeFeedrate()

WrapperModule Jogger IsJogModeFeedrate ( )

Check whether this Jogger is in feedrate jog mode.

Returns true if the current jog mode is 3 (Feedrate mode).

Returns
(boolean) True if the Jogger is in feedrate mode, false otherwise
See also
WrapperModule.Jogger:SetJogModeFeedrate() to activate feedrate mode
Note
Documentation generated by AI on 2026-03-04

◆ IsJogModeIncremental()

WrapperModule Jogger IsJogModeIncremental ( )

Check whether this Jogger is in incremental jog mode.

Returns true if the current jog mode is 1 (Incremental mode).

Returns
(boolean) True if the Jogger is in incremental mode, false otherwise
See also
WrapperModule.Jogger:SetJogModeIncremental() to activate incremental mode
Note
Documentation generated by AI on 2026-03-04

◆ IsLatheCCLicensed()

WrapperModule IsLatheCCLicensed ( )

Check whether the LatheCC feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "LatheCC" feature.

Returns
(boolean) True if LatheCC is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsLimitSwitchActive()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) True (axis enabled state) if a limit switch is active, false if all clear, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message indicating which axis limit is active or that all are clear
See also
WrapperModule.IsHomeSwitchActive() for checking home switches
WrapperModule.GetMotorParentAxisID() to find the axis associated with a motor
Note
Documentation generated by AI on 2026-03-04

◆ IsLuaRunningInMCodeChunk()

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.

Returns
(boolean) True if the Lua code is running in an M-code chunk, false otherwise
See also
WrapperModule.IsLuaRunningInScreenChunk() for the screen chunk equivalent
Note
Documentation generated by AI on 2026-03-04

◆ IsLuaRunningInScreenChunk()

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).

Returns
(boolean) True if the Lua code is running in a screen chunk, false otherwise
See also
WrapperModule.IsLuaRunningInMCodeChunk() for the M-code chunk equivalent
Note
Documentation generated by AI on 2026-03-04

◆ IsMachInitialized()

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.

Returns
(boolean) True if the MachMotion plugin has completed initialization, false otherwise
Note
The result is cached after the first successful "1" response from the plugin
Documentation generated by AI on 2026-03-04

◆ IsMachMotionLicensed()

WrapperModule IsMachMotionLicensed ( )

Check whether the MachMotion base feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "MachMotion" feature.

Returns
(boolean) True if MachMotion is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsMachShuttingDown()

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.

Returns
(boolean) True if Mach is shutting down or the config register is unavailable, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ IsManualToolSetterEnabled()

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.

Returns
(boolean) True if at least one manual tool setter is configured, false otherwise
See also
WrapperModule.GetAllManualToolSetters() to retrieve the full list of manual tool setters
WrapperModule.IsAutoToolSetterEnabled() for the auto setter equivalent
Note
Documentation generated by AI on 2026-03-04

◆ IsMCodeHoldActive()

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.

Returns
(boolean) True if the MCode hold count is greater than zero, false otherwise
See also
WrapperModule.RequestMCodeHold() to request a hold
WrapperModule.ReleaseMCodeHold() to release a hold
Note
Documentation generated by AI on 2026-03-04

◆ IsMotorMappedToAxis()

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.

Parameters
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
Returns
(boolean|nil) True if MotorID is mapped to AxisID, false otherwise, nil on error
(boolean) Success flag - true if the check completed (regardless of whether motor is mapped)
(string) Status message describing the result
See also
WrapperModule.GetAxisChildMotorID() for the list of motors on an axis
WrapperModule.GetMotorParentAxisID() to find which axis a motor belongs to
Note
Documentation generated by AI on 2026-03-04

◆ IsMultiInstance()

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.

Returns
(boolean) True if more than one Mach4 instance is running, false otherwise
See also
WrapperModule.GetInstanceCount() for retrieving the raw instance count
Note
Documentation generated by AI on 2026-03-04

◆ IsOEMParamSigMapped()

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.

Parameters
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
Returns
(boolean|nil) True if a signal or I/O is mapped, false if unmapped, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message describing the result
See also
WrapperModule.IsParamSigMapped() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsOperatorPanelJogging()

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.

Parameters
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
Returns
(boolean) True if the operator panel is jogging the specified axis, false otherwise
See also
WrapperModule.GetConfiguredOperatorPanels() for checking which panels are configured
Note
Documentation generated by AI on 2026-03-04

◆ IsParamSigMapped()

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.

Parameters
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
Returns
(boolean|nil) True if a signal or I/O is mapped, false if unmapped, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ IsProbeEnabledOutputOn()

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).

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the probe enable output signal is active or not mapped, false if mapped and inactive
Note
Documentation generated by AI on 2026-03-04

◆ IsProbeErrorInputOn()

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).

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the probe error input signal is active, false if inactive or not mapped
Note
Documentation generated by AI on 2026-03-04

◆ IsRMPLicensed()

WrapperModule IsRMPLicensed ( )

Check whether the RMP feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "RMP" feature.

Returns
(boolean) True if RMP is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ IsSignalMapped()

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.

Parameters
Signal(number) The signal ID to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) True if the signal is mapped to an I/O handle, false if unmapped, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message describing the result
See also
WrapperModule.IsSignalMappedAndEnabled() for checking both mapping and enabled state
WrapperModule.eIsSignalMapped() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ IsSignalMappedAndEnabled()

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.

Parameters
Signal(number) The signal ID to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean|nil) True if the signal is both mapped and enabled, false if either condition fails, nil on error
(boolean) Success flag - true if the check completed successfully
(string) Status message describing the result
See also
WrapperModule.IsSignalMapped() for checking mapping without checking enabled state
WrapperModule.eIsSignalMappedAndEnabled() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ IsSimMotionController()

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".

Returns
(boolean) True if the motion controller is a simulator (Sim0 or SimDev0), false otherwise
See also
WrapperModule.GetMotionController() for retrieving the motion device name
Note
Documentation generated by AI on 2026-03-04

◆ IsSpindleSpeedVariationOn()

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.

Returns
(boolean) True if Spindle Speed Variation is enabled (parameter 1940 == 1), false otherwise
See also
WrapperModule.SpindleSpeedVariation() to enable or disable SSV
WrapperModule.SpindleSpeedVariationToggle() to toggle SSV state
Note
Documentation generated by AI on 2026-03-04

◆ IsTableInRegister()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if a table is present in the register, false if the register is empty
See also
WrapperModule.SendTableAcrossRegister() to write a table into the register
WrapperModule.ReadTableRegister() to read and clear the register contents
Note
Documentation generated by AI on 2026-03-04

◆ IsToolChangerOverrideOn()

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".

Parameters
tool_number(number) The tool number to check
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if a tool changer override is active for the tool, false if no override is set
See also
WrapperModule.GetToolChangerOverride() for the string override value
Note
Documentation generated by AI on 2026-03-04

◆ IsToolDrillTool()

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.

Parameters
tool(number) The tool number to check against configured drill banks
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the tool belongs to a drill bank, false otherwise
(number|nil) The bank number (1 or 2) if found, nil if not found
See also
WrapperModule.InterpretRangeString() for the range string format
Note
Documentation generated by AI on 2026-03-04

◆ IsToolPathGenerating()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the tool path is currently generating, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ IsToolSetterAuto()

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.

Parameters
ToolSetterName(string) The name of the tool setter to check
Returns
(boolean) True if the tool setter is an auto setter, false if it is a manual setter
See also
WrapperModule.GetToolSetterType() for a string representation of the setter type
WrapperModule.GetAllAutoToolSetters() to retrieve all auto setters
Note
Documentation generated by AI on 2026-03-04

◆ IsToolTableInitialized()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(boolean) True if the tool table file exists and contains a valid 'Properties.Type' entry
(boolean) Always true for the success flag
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetToolTableFileName() for the tool table file path
Note
Documentation generated by AI on 2026-03-04

◆ IsToolTableUserField()

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.

Parameters
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
Returns
(boolean) True if the field name exists in the tool table, false otherwise
(boolean) Always true for the success flag
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.IsToolTableUserFieldList() to check multiple field names at once
WrapperModule.AddToolTableUserField() to add a new user field to the tool table
Note
Documentation generated by AI on 2026-03-04

◆ IsToolTableUserFieldList()

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.

Parameters
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
Returns
(boolean) True if all field names in field_list exist in the tool table, false if any are missing
(boolean) Always true for the success flag
(string) Status message from w.FunctionCompleted() or a description of the missing field
See also
WrapperModule.IsToolTableUserField() to check a single field name
WrapperModule.AddToolTableUserFieldList() to add multiple user fields at once
Note
Documentation generated by AI on 2026-03-04

◆ IsYaskawaLicensed()

WrapperModule IsYaskawaLicensed ( )

Check whether the Yaskawa feature is licensed.

Convenience wrapper around w.IsFeatureLicensed() that checks for the "Yaskawa" feature.

Returns
(boolean) True if Yaskawa is licensed, false otherwise
See also
WrapperModule.IsFeatureLicensed() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ itself()

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().

◆ JogABS()

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.

Parameters
position(number) The absolute machine position to jog to
feedrate(number) The commanded feedrate in units/minute. Clamped to min/max limits
See also
WrapperModule.Jogger:JogABSWait() to jog to an absolute position and wait for completion
WrapperModule.Jogger:SetJogModeABS() for ABS mode details
Note
Documentation generated by AI on 2026-03-04

◆ JogABSWait()

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.

Parameters
position(number) The absolute machine position to jog to
feedrate(number) The commanded feedrate in units/minute. Clamped to min/max limits
Warning
This function blocks execution until the axis reaches the target position
See also
WrapperModule.Jogger:JogABS() for the non-blocking version
WrapperModule.Jogger:Wait() for the blocking wait logic
Note
Documentation generated by AI on 2026-03-04

◆ JogBasedOnMode()

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.

Parameters
direction(number|nil) The jog direction: 1 for positive, -1 for negative. Defaults to 1 if nil
See also
WrapperModule.Jogger:JogVelocity() for explicit velocity jogging
WrapperModule.Jogger:JogIncremental() for explicit incremental jogging
WrapperModule.Jogger:IsJogModeContinuous() to check the current mode
Note
Documentation generated by AI on 2026-03-04

◆ JogIncremental()

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.

Parameters
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
Warning
Raises an error via w.Error() if increment is nil
See also
WrapperModule.Jogger:SetJogModeIncremental() for incremental mode details
WrapperModule.Jogger:JogStop() to stop an in-progress jog
Note
Documentation generated by AI on 2026-03-04

◆ JogRotaryFeedrate()

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.

Parameters
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
See also
WrapperModule.Jogger:JogStop() to stop the jog
WrapperModule.Jogger:CalculateFeedrate() for feedrate limit and override calculations
Note
Documentation generated by AI on 2026-03-04

◆ JogStop()

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.

See also
WrapperModule.Jogger:Stop() for a mode-aware stop that checks jog state
WrapperModule.Jogger:StopWait() to stop and wait until motion has fully ceased
Note
Documentation generated by AI on 2026-03-04

◆ JogVelocity()

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.

Parameters
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
See also
WrapperModule.Jogger:JogStop() to stop the velocity jog
WrapperModule.Jogger:SetJogModeContinuous() for continuous mode details
Note
Documentation generated by AI on 2026-03-04

◆ JoinArgs() [1/2]

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.

Parameters
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
Returns
(string) Concatenated string of arguments, or stringified table if 'n' field is missing
-- Join all arguments with default delimiter
local packed = table.pack("X", 10.5, "Y", 20)
local str = w.JoinArgs(packed) -- Returns "X; 10.5; Y; 20"
-- Custom delimiter
local str = w.JoinArgs(packed, ", ") -- Returns "X, 10.5, Y, 20"
-- Skip first argument
local str = w.JoinArgs(packed, ", ", 2) -- Returns "10.5, Y, 20"
Path Join(...)
Note
Documentation generated by AI on 2026-03-04

◆ JoinArgs() [2/2]

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.

Parameters
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
Returns
(string) Concatenated string of arguments, or stringified table if 'n' field is missing
-- Join all arguments with default delimiter
local packed = table.pack("X", 10.5, "Y", 20)
local str = w.JoinArgs(packed) -- Returns "X; 10.5; Y; 20"
-- Custom delimiter
local str = w.JoinArgs(packed, ", ") -- Returns "X, 10.5, Y, 20"
-- Skip first argument
local str = w.JoinArgs(packed, ", ", 2) -- Returns "10.5, Y, 20"
Note
Documentation generated by AI on 2026-03-03

◆ key_to_str() [1/2]

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.

Parameters
k(any) The table key to convert
Returns
(string) The string representation of the key, suitable for use in a Lua table literal
See also
WrapperModule.table.val_to_str() for value formatting
WrapperModule.table.repr() for the full compact table formatter
Note
Documentation generated by AI on 2026-03-04

◆ key_to_str() [2/2]

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.

Parameters
k(any) The table key to convert to a string
indent(string|nil) The indentation prefix string. Defaults to "" if nil
Returns
(string) The indented string representation of the key
See also
WrapperModule.table.pretty.val_to_str() for value formatting
WrapperModule.table.pretty.repr() for the full table pretty-printer
Note
Documentation generated by AI on 2026-03-04

◆ LLLog()

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().

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ Load()

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.

Parameters
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
Returns
(any|nil) The return value of require(basename), or nil if the file was not found
See also
WrapperModule.LoadOpStatus() for an example of this function in use
WrapperModule.PackagePath() for the related package path management function
Note
Documentation generated by AI on 2026-03-04

◆ LoadGCodeFile()

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.

Parameters
filenameThe path to the GCode file to load.
instThe instance number to load the file into. If not provided, the current instance is used.
Note
Documentation generated by AI on 2026-03-03
Parameters
instThe instance number to load the file into. If not provided, the current instance is used.

◆ LoadOpStatus()

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.

Parameters
force(boolean|nil) If true, forces the module to reload even if already loaded. Defaults to false
See also
WrapperModule.Load() for the underlying module loading mechanism
Note
Documentation generated by AI on 2026-03-04

◆ LoadVersionInfo()

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).

Warning
Overwrites the global MACH_VERSION_INFO table each time it is called
See also
WrapperModule.GetVersionInfo() to read individual components from the loaded table
Note
Documentation generated by AI on 2026-03-04

◆ Log()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ LogC()

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.

Parameters
...(any) Variable number of values to log. Each is converted with tostring()
See also
WrapperModule.Log() for the underlying logging function
WrapperModule.LogF() for printf-style formatted logging
Note
Documentation generated by AI on 2026-03-04

◆ LogF()

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.

Parameters
fmt(string) A string.format() format string
...(any) Arguments to substitute into the format string
See also
WrapperModule.Log() for the underlying logging function
WrapperModule.LogC() for concatenation-style logging
Note
Documentation generated by AI on 2026-03-04

◆ LogMultiline()

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.

Parameters
message(string) The multi-line message to log
indent(string|nil) An optional prefix string prepended to each line. Defaults to "" if nil
See also
WrapperModule.Log() for the underlying single-line logging function
Note
Documentation generated by AI on 2026-03-04

◆ LogoutPassword()

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.

See also
WrapperModule.PasswordProtection() which reads these keys to check for active sessions
Note
Documentation generated by AI on 2026-03-04

◆ MakeDirectory()

WrapperModule MakeDirectory ( Path )

Create the target directory and all nonexistent ancestor directories.

WrapperModule.MakeDirectory

Note
Documentation generated by AI on 2026-03-03

Create the target directory and all nonexistent ancestor directories.

◆ MakeNewFileQueue()

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.

Returns
(table) A new LuaFileQueue instance ready for AddCommand() and GetReply() calls
See also
WrapperModule.PostToFileQueue() for posting commands via the file queue
Note
Documentation generated by AI on 2026-03-04

◆ MapMotorsToAxis()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.UnMapMotorsFromAxis() to remove a motor from an axis
WrapperModule.ApplyMotorMappingsToMotionController() to apply mapping changes to the motion controller
Note
Documentation generated by AI on 2026-03-04

◆ MarkAxisAsHomedIfMotorsAreHomed()

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.

Parameters
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
Note
This function has no return value; it silently returns if the axis is already homed or no motors are mapped
See also
WrapperModule.IsAxisHomed() for the full homed status check including OEM parameter validation
WrapperModule.GetAxisChildMotorID() to retrieve the motors mapped to an axis
Note
Documentation generated by AI on 2026-03-04

◆ MCodeError()

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.

Parameters
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
Warning
This function always raises an error and never returns. Callers must use pcall/xpcall protection
-- Raise M-code error with context
if spindle_speed > MAX_SPEED then
w.MCodeError("Spindle speed exceeds maximum", "M3.mcs", 42)
end
See also
WrapperModule.Error() for screen chunk error handling
WrapperModule.AlarmError() for GMS alarm delivery
Note
Documentation generated by AI on 2026-03-04

◆ MDICommand()

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.

Parameters
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
Returns
(string|nil) The executed command string, or nil on error
(boolean) Success flag - true if the command completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Machine must be enabled before calling this function
See also
WrapperModule.MDICommandNoDialog() for the no-dialog equivalent
WrapperModule._MDICommand() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ MDICommandNoDialog()

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.

Parameters
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
Returns
(string|nil) The executed command string, or nil on error
(boolean) Success flag - true if the command completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Machine must be enabled before calling this function
See also
WrapperModule.MDICommand() for the dialog-based equivalent
WrapperModule._MDICommand() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ mean()

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.

Returns
(number) The arithmetic mean of the stored sample values, or 0 if no data exists
See also
WrapperModule.Averager:trend() for a trend-line based smoothed value
WrapperModule.Averager:sample() to add values and retrieve the mean
Note
Documentation generated by AI on 2026-03-04

◆ mean_x()

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.

Returns
(number) The mean of the x-index sequence: (num_points + 1) / 2
See also
WrapperModule.Averager:trend() for usage in regression calculations
Note
Documentation generated by AI on 2026-03-04

◆ merge()

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.

Parameters
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
Returns
(table) The modified t1 table with all entries from t2 merged in
local defaults = {color = "red", size = 10, sub = {a = 1}}
local overrides = {size = 20, sub = {b = 2}}
w.table.merge(defaults, overrides)
-- defaults = {color = "red", size = 20, sub = {a = 1, b = 2}}
Note
Documentation generated by AI on 2026-03-04

◆ MessageBox()

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.

Parameters
message(string) The message text to display in the dialog
...(any) Additional arguments passed to wx.wxMessageBox() (e.g., caption, style, parent)
Returns
(number) The wx message box result code (e.g., wx.wxOK, wx.wxCANCEL, wx.wxYES, wx.wxNO)
See also
WrapperModule.wxMessageBox() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ MessageDialog()

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.

Parameters
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"
Returns
(string|nil) The name of the button pressed ("OK", "Yes", "No", "Cancel"), or nil if closed without a button
(boolean) Success flag - always true
(string) Status message describing which button was pressed or how the dialog was closed
Note
Documentation generated by AI on 2026-03-04

◆ MoveAxisIntoSoftLimitZone()

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.

Parameters
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
Returns
(boolean) True if the axis is within soft limits (either already was, or after the move)
Warning
This function blocks execution until the axis reaches the target position
See also
WrapperModule.IsAxisInSideSoftLimitsZone() to check whether an axis is within its soft limits
Note
Documentation generated by AI on 2026-03-04

◆ name() [1/3]

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() [2/3]

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.

Parameters
caller_level(number|nil) The starting stack level to inspect. Defaults to 2 if not a number

◆ name() [3/3]

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, ...).

◆ New()

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.

Parameters
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
Returns
(table) A new Jogger instance configured for the specified axis
-- Create a Jogger for the Z axis and jog to an absolute position
local jogger = w.Jogger.New(mc.Z_AXIS)
jogger:JogABSWait(-10.0, jogger.max_rate)
WrapperModule Jogger JogABSWait(feedrate)
Jog the axis to an absolute position and block until the move is complete.
Warning
Raises an error via w.Error() if the axis is invalid or not enabled
Note
Documentation generated by AI on 2026-03-04

◆ new() [1/2]

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.

Parameters
name(string) A descriptive name for this checkpoint object (used in tostring() output)
Returns
(table) A new DbgCheckPoint instance
-- Create a checkpoint tracker for a function
_fn_check = w.DbgCheckPoint:new('MyFunction')
_fn_check:CHECK('Start')
-- ... do work ...
_fn_check:CHECK('Finished')
WrapperModule DbgCheckPoint CHECK(descr, value)
Record a checkpoint with an optional description and value.
Note
Documentation generated by AI on 2026-03-04

◆ new() [2/2]

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.

Parameters
num_points(number) The maximum number of data points to retain in the sliding window
Returns
(table) A new Averager instance with sample, mean, trend, variance, stdev, and covariance methods
-- Create an averager with a 50-point window
local avg = w.Averager.new(50)
local running_avg = avg:sample(sensor_value)
local trend_value = avg:trend()
WrapperModule Averager sample(value_op)
Add a sampled value to the window and return a summary statistic.
WrapperModule Averager trend()
Calculate the trend line value using least squares linear regression.
Note
Documentation generated by AI on 2026-03-04

◆ NewSerialConnection()

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:

  • write(stringdata, timeout): Write raw string data
  • writeBcc(stringdata, timeout): Write with BCC checksum appended
  • read(read_len, timeout): Read bytes from the port
  • request(cmd, read_len, timeout): Write then read
  • requestBcc(cmd, read_len, timeout): WriteBcc then read
  • close(): Close the port
  • bccCheckSum(str): Compute BCC checksum
    Parameters
    portnumber(number) The COM port number to open (e.g., 3 for COM3)
    setup(table|nil) Optional serial port configuration table with keys:
  • baud (number): Baud rate (50-921600). Default: 9600
  • databits (number): Data bits (5, 6, 7, or 8). Default: 8
  • stopbits (number): Stop bits (1 or 2). Default: 1
  • parity (string): Parity ('none', 'odd', 'even'). Default: 'none'
  • flowcontrol (string): Flow control ('none', 'xon/xoff', 'hardware'). Default: 'none'
    Parameters
    error_codes(table|nil) Optional table of project-specific error codes attached to the wrapper
    Returns
    (table) A serial connection wrapper table with read/write/close methods
    -- Open COM3 at default settings (9600 8N1)
    local serial = w.NewSerialConnection(3)
    serial:write("Hello\r\n")
    local response, len = serial:read(10, 2000)
    serial:close()
    -- Open COM5 at 115200 baud
    local serial = w.NewSerialConnection(5, {baud=115200, databits=8, stopbits=1, parity="none"})
    CommonGUIModule JobFile Open()
    Open a file browser dialog to select and load a job file, then apply it to Mach4.
    wrapper read(self, read_len, timeout)
    Read data from the serial port.
    wrapper write(self, stringdata, timeout)
    Write a string to the serial port.
    WrapperModule NewSerialConnection(portnumber, setup, error_codes)
    Create and configure a new serial port connection wrapper.
    wrapper close(self)
    Close the serial port connection.
Warning
Raises an error via w.Error() if the port cannot be opened or configured
Note
Documentation generated by AI on 2026-03-04

◆ nice_decimal()

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.

Parameters
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
Returns
(string) Formatted string representation with insignificant zeros removed
-- Default precision
local s = w.nice_decimal(3.14159) -- Returns "3.1416"
-- Integer result (trailing zeros and decimal removed)
local s = w.nice_decimal(2.0) -- Returns "2"
-- With width for column alignment
local s = w.nice_decimal(1.5, 4, 8) -- Returns "1.5 " (padded to width 8)
Note
Documentation generated by AI on 2026-03-04

◆ NPPEditor()

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).

Parameters
path_to_nppexe(string) Full path to the Notepad++ executable
Returns
(function) A function that accepts a file path string and returns a batch command string
See also
WrapperModule.CreateOrOpenFile() which accepts the returned function as the editor parameter
WrapperModule.GCEditEditor() for the equivalent GCEdit editor factory
Note
Documentation generated by AI on 2026-03-04

◆ open_cmd()

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().

Parameters
url(string) The URL or file path to open
Returns
(boolean) True if the open command succeeded (exit code 0), false otherwise
Note
Documentation generated by AI on 2026-03-04

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.

Parameters
url(string) The URL or file path to open
Returns
(boolean) True if xdg-open was successfully launched, false otherwise
Note
Documentation generated by AI on 2026-03-04

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.

Parameters
url(string) The URL or file path to open
Returns
(boolean) True if the open command was successfully launched, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ OpenFileHelper()

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.

Returns
(table) The FileHelper module table
Note
Documentation generated by AI on 2026-03-04

◆ OpenURL()

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.

Parameters
url(string) The URL or file path to open
Returns
(boolean) True if the open command was successfully launched, false otherwise
Note
Documentation generated by AI on 2026-03-04

◆ OperatorLog()

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().

Parameters
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()
See also
WrapperModule.SetStatus() for setting the status message without operator logging
Note
Documentation generated by AI on 2026-03-04

◆ PackagePath()

WrapperModule PackagePath ( paths ,
update_cpath  )

◆ Parabola()

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.

Parameters
x0the starting point (x0,0)
x1the ending point (x1,0)
y_maxthe peak/vertex of the parabola ((x0+x1)/2,y_max)
Note
Documentation generated by AI on 2026-03-03
Parameters
y_maxthe peak/vertex of the parabola ((x0+x1)/2,y_max)

◆ ParseAnalogSignalPath()

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.

Parameters
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
Returns
(table|nil) Table with keys: 'type' (string - "Analog Input Signal" or "Analog Output Signal"), 'signal_id' (number), 'instance' (number). Returns nil if no selection
Note
Documentation generated by AI on 2026-03-04

◆ ParseCSVLine()

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.

Parameters
line(string) The CSV line string to parse
sep(string|nil) The field separator character. If nil, defaults to ','
Returns
(table) Array of parsed field value strings
(number) The number of fields parsed from the line
Note
Documentation generated by AI on 2026-03-04

◆ ParseGCodeLine()

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.

Parameters
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
Returns
(table|nil) Table mapping each keyword to its extracted numeric value (or nil if absent), or nil on error
(boolean) Success flag - true if parsing completed, false if Line or Keywords is nil
(string) Status message describing the result
-- Parse standard axis positions
local values, success, msg = w.ParseGCodeLine("G00 X1.5 Y2.0 Z-0.5")
-- values = {X=1.5, Y=2.0, Z=-0.5, F=nil, S=nil}
-- Parse custom keywords
local values, success, msg = w.ParseGCodeLine("G02 I0.5 J1.0", {"I", "J"})
-- values = {I=0.5, J=1.0}
Note
Documentation generated by AI on 2026-03-04

◆ parseINI()

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.

Parameters
name(string) Full path to the INI file to read
Returns
(table|nil) Two-level table where t[section][key] = value, or nil if the file could not be opened
Note
Documentation generated by AI on 2026-03-04

References name().

◆ ParseIOSigPath()

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)".

Parameters
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
Returns
(table|nil) Parsed object table with keys:
  • type (string): Object type description
  • instance (number): Mach4 instance number
  • IsOutputSignal (boolean), IsInputSignal (boolean), IsIO (boolean), IsAnalogOutputSignal (boolean), IsAnalogInputSignal (boolean), IsRegister (boolean)
  • sigid (number): Signal ID (for signal types)
  • device (string): Device name (for IO and Register types)
  • name (string): Object name (for IO and Register types) Returns nil if path indicates no selection
Note
Documentation generated by AI on 2026-03-04

◆ parseISO8601Timestamp()

WrapperModule parseISO8601Timestamp ( str )

parse a timestamp formatted as an ISO8601 string.

WrapperModule.parseISO8601Timestamp

Returns
a (possibly float, if the timestamp has fractional seconds) timestamp like one returned by os.time().
Parameters
ts_strThe 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.

Note
Documentation generated by AI on 2026-03-03

◆ ParseMultipleReturnValuesFromFileQueueResponse()

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).

Parameters
value_from_user(string|nil) A comma-delimited string of "key:value" pairs from a file queue response
Returns
(table) Result table with keys: show_modal_rc (boolean|nil), user_value (number|string|nil), additional_data (table)
-- Parse a file queue response string
local result = w.ParseMultipleReturnValuesFromFileQueueResponse("ShowModalRC:true, value:123.456, extra1:789")
-- result.show_modal_rc = true
-- result.user_value = 123.456
-- result.additional_data.extra1 = 789
Note
Documentation generated by AI on 2026-03-04

◆ ParseRegHandle()

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 "/").

Parameters
path(string) The full path string to parse, e.g. "MachMotion/MyRegister"
Returns
(string) The device portion of the path (everything before the last "/")
(string) The name portion of the path (everything after the last "/")
Note
Documentation generated by AI on 2026-03-04

◆ ParseRegisterPath()

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)".

Parameters
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
Returns
(table|nil) Table with keys: 'device' (string), 'name' (string), 'instance' (number). Returns nil if no selection
Note
Documentation generated by AI on 2026-03-04

◆ ParseStructuredGCodeComment()

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).

Parameters
comment_string(string) The raw G-code comment text to parse (without surrounding parentheses)
Returns
(table) Result table with keys:
  • comment (string): The plain text portion before DATA: (whitespace-trimmed), or the full string if no DATA: found
  • data (any): The evaluated Lua expression result, or nil if no DATA: or on evaluation error
  • error (boolean): True if the DATA: expression could not be parsed or evaluated
  • error_message (string): The error message if parsing/evaluation failed, empty otherwise
-- Parse a comment with data
local result = w.ParseStructuredGCodeComment("My comment DATA:{x=1, y=2}")
-- result.comment = "My comment"
-- result.data = {x=1, y=2}
-- Parse a plain comment (no data)
local result = w.ParseStructuredGCodeComment("Simple comment")
-- result.comment = "Simple comment"
-- result.data = nil
Note
Documentation generated by AI on 2026-03-04

◆ PasswordProtection()

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.

Parameters
level(number) The required access level to check (1, 2, or 3). Clamped to 1-3 range
Returns
(boolean) True if the user authenticated successfully or no password is required
(boolean) Success flag - true if the function completed without error
(string) Status message describing the result
Note
The stay-logged-in feature uses mc.mcProfileGetInt/WriteInt to persist session state
See also
WrapperModule.LogoutPassword() to invalidate an active password session
Note
Documentation generated by AI on 2026-03-04

◆ pcall()

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.

-- Protect a function call and handle errors
local is_ok, err = w.pcall(user.MyFunc, arg1, arg2)
if not is_ok then
w.LogF("Error invoking MyFunc: %s", w.ErrorMessage(err))
end
See also
WrapperModule.ErrorHandler() for the underlying error handler
WrapperModule.Error() for the error object format
Note
Documentation generated by AI on 2026-03-04

◆ PleaseWaitDialog()

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.

Parameters
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)
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if condition was met, false if canceled, timed out, or errored
(string) Status message describing the outcome
Warning
Only one PleaseWaitDialog may be active at a time. Calling this while one is already open raises a Lua error
Canceling a MachState wait type will disable the machine
See also
WrapperModule.WaitOnCondition() for a non-dialog version
WrapperModule.PleaseWaitType for the available wait type constants
Note
Documentation generated by AI on 2026-03-04

◆ PopulateAPI()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ PostCommand()

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.

Parameters
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
Returns
(string) The file queue command handle
See also
WrapperModule.PostToFileQueue() for posting arbitrary Lua strings
WrapperModule.WaitForFileQueueResponse() for blocking until the command completes
Note
Documentation generated by AI on 2026-03-04

◆ PostToFileQueue()

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.

Parameters
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
Returns
(string) The file queue command handle for use with w.WaitForFileQueueResponse()
See also
WrapperModule.WaitForFileQueueResponse() for blocking until the command completes
WrapperModule.PostCommand() for posting named user commands via the file queue
Note
Documentation generated by AI on 2026-03-04

◆ pow()

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.

Parameters
val(number) The base value
exponent(number) The exponent to raise val to
Returns
(number) The result of val raised to the power of exponent
Note
Documentation generated by AI on 2026-03-04

◆ PretendCommandsAreFromOperatorPanels()

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).

Returns
(boolean) True if commands should be treated as operator panel commands, false otherwise
Note
This function is used to bypass screen-level safety features in simulator and touchscreen-free configurations
Documentation generated by AI on 2026-03-04

◆ Print()

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.

Note
Documentation generated by AI on 2026-03-04

◆ PrintDebugMessage()

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.

Parameters
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
Returns
(string) The CustomMessage string (after tostring conversion)
Note
Documentation generated by AI on 2026-03-04

◆ ProcessActiveCommand()

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.

Parameters
command_name(string) The name of the command being processed
command_table(table) The command configuration table containing FeedbackCheckPeriod, FeedbackNextCheck, and LastState fields
Note
Documentation generated by AI on 2026-03-04

◆ ProcessActiveCommandFeedback()

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.

Parameters
feedback_name(string) The name of the command feedback to process
Note
Documentation generated by AI on 2026-03-04

◆ ProcessActiveCommands()

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.

Note
This function is intended to be called from the screen update loop (e.g., every screen refresh)
Documentation generated by AI on 2026-03-04

◆ Protected()

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.

Parameters
...(any) The function to call followed by its arguments (same signature as pcall)
Returns
(...) All return values from the protected function call on success, or nothing on error
See also
WrapperModule.ProtectedMsg() for context-sensitive error reporting
WrapperModule.ProtectedChk() for the full implementation with checkpoint support
Note
Documentation generated by AI on 2026-03-04

◆ ProtectedChk()

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.

Parameters
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)
Returns
(...) All return values from the protected function call on success, or nothing on error
Note
Documentation generated by AI on 2026-03-04

◆ ProtectedMsg()

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.

Parameters
...(any) The function to call followed by its arguments (same signature as pcall)
Returns
(...) All return values from the protected function call on success, or nothing on error
See also
WrapperModule.ProtectedChk() for the full implementation
WrapperModule.Protected() for always showing full debug messages
Note
Documentation generated by AI on 2026-03-04

◆ read()

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.

Parameters
read_len(number) The number of bytes to attempt to read
timeout(number|nil) Timeout in milliseconds. If nil, defaults to 5000ms
Returns
(string) The data read from the serial port
(number) The number of bytes actually read
Warning
Raises an error via w.Error() if a read failure occurs
Note
Documentation generated by AI on 2026-03-04

◆ ReadCSV()

WrapperModule ReadCSV ( FileName ,
options  )

◆ ReadCSVIntoTableByHeader()

WrapperModule ReadCSVIntoTableByHeader ( filename ,
options  )

◆ ReadGcodeHeaderParameters()

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.

Parameters
gcode_file(string|nil) Full path to the G-code file to parse. If nil, reads from the currently loaded G-code in Mach
Returns
(table) Nested table of parsed key-value parameters (may be empty if no parameters found)
(boolean) True if any parameter data was found, false if no "(Start Parameters)" block was present
(string) Status message describing the result
-- Parse parameters from a file
local params, has_data, msg = w.ReadGcodeHeaderParameters("C:\\GCode\\part.nc")
-- params["Tool"]["Number"] = "1"
-- Parse from currently loaded G-code
local params, has_data, msg = w.ReadGcodeHeaderParameters(nil)
Note
Documentation generated by AI on 2026-03-04

◆ ReadListHistory()

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.

Parameters
filename(string) Full path to the history file to read
Returns
(table) An array of history line strings, with \n sequences converted back to newlines
See also
WrapperModule.AddToListHistory() which writes entries to the history file
Note
Documentation generated by AI on 2026-03-04

◆ ReadTableRegister()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string|nil) The raw serialized table string read from the register, or nil on error
(boolean) Success flag - true if the register was read and cleared successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SendTableAcrossRegister() to write a table into the register
WrapperModule.IsTableInRegister() to check whether a table is present
Note
Documentation generated by AI on 2026-03-04

◆ ReadTextFile()

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.

Parameters
FileName(string) Full path to the text file to read
Returns
(string|nil) The complete file contents as a string, or nil if the file could not be opened
(boolean) Success flag - true if file was read successfully, false if file could not be opened
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ ReadUserCommandFile()

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.

Parameters
filepath(string) Full path to the user command INI file to read
Returns
(table) Table mapping section names (string) to command configuration sub-tables
See also
WrapperModule.GetAllUserCommands() for reading all command files in the folder
WrapperModule.SaveUserCommand() for writing a command file
Note
Documentation generated by AI on 2026-03-04

◆ ReceiveTableAcrossRegister()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table|nil) The deserialized table data, or nil if the register is empty or on error
(boolean) Success flag - true if a table was received successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SendTableAcrossRegister() to write a table into the register
WrapperModule.ReceiveTableAcrossRegisterWait() for the blocking version
Note
Documentation generated by AI on 2026-03-04

◆ ReceiveTableAcrossRegisterWait()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(table|nil) The deserialized table data, or nil on error
(boolean) Success flag - true if a table was received successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
This function blocks execution until a table is available in the register
See also
WrapperModule.SendTableAcrossRegister() to write a table into the register
WrapperModule.ReceiveTableAcrossRegister() for the non-blocking version
Note
Documentation generated by AI on 2026-03-04

◆ Recursive()

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.

Parameters
t(table) A condition set table with keys: 'Set' (number 0-2), 'Conditions' (table), and optionally 'Sets' (table of nested condition sets)
Returns
(string) The serialized condition set string for inclusion in the GMS CreateMonitor command
See also
WrapperModule.CreateSystemGlobalMessage() for the enclosing function context
Note
Documentation generated by AI on 2026-03-04

◆ RegenerateToolPathDialog()

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.

Parameters
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
Returns
(number|nil) The wx modal result code (wx.wxID_OK or wx.wxID_CANCEL), or nil in non-modal mode
(boolean|nil) True if the dialog was shown, nil in non-modal mode or on error
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
The machine must be in IDLE state before calling this function
Note
Documentation generated by AI on 2026-03-04

◆ Register()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

References func().

◆ RegSendCommand()

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.

Parameters
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
Returns
(string|nil) The response string from the register command, or nil on error
(boolean) Success flag - true if the command was sent and responded successfully
(string) Status message describing the result
See also
WrapperModule.eRegSendCommand() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ ReleaseCycleStartHold()

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.

Parameters
reason(string|nil) A description of why the hold is being released. Defaults to "Unknown" if nil
Returns
(boolean) True indicating the hold was released
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.RequestCycleStartHold() to activate a Cycle Start Hold
WrapperModule.ReleasedForCycleStart() to check the release reason afterward
Note
Documentation generated by AI on 2026-03-04

◆ ReleasedForCycleStart()

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).

Returns
(boolean) True if the last hold release reason was "Cycle Start", false otherwise
See also
WrapperModule.ReleaseCycleStartHold() to release a hold and set the reason
WrapperModule.IsCycleStartHoldActive() to check whether a hold is currently active
Note
Documentation generated by AI on 2026-03-04

◆ ReleaseInhibitJogOnAllAxes()

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.

Parameters
release_all(boolean|nil) If true, forces all inhibit counters to 0
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.InhibitJogOnAllAxes() to inhibit jogging on all axes
WrapperModule.ReleaseInhibitJogOnAxis() for per-axis inhibit release
Note
Documentation generated by AI on 2026-03-04

◆ ReleaseInhibitJogOnAxis()

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.

Parameters
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
See also
WrapperModule.InhibitJogOnAxis() to increment the jog inhibit counter
WrapperModule.IsInhibitJogOnAxis() to check whether jogging is currently inhibited
Note
Documentation generated by AI on 2026-03-04

◆ ReleaseInhibitJogOnCoordinatedAxes()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.InhibitJogOnCoordinatedAxes() to inhibit jogging on coordinated axes
WrapperModule.ReleaseInhibitJogOnAllAxes() to release inhibit on all axes including OB axes
Note
Documentation generated by AI on 2026-03-04

◆ ReleaseMCodeHold()

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.

Returns
(number) The updated hold counter value after decrement
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.RequestMCodeHold() to increment the hold counter
WrapperModule.IsMCodeHoldActive() to check whether a hold is currently active
Note
Documentation generated by AI on 2026-03-04

◆ RemoveActiveDialog()

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.

Parameters
dlg_name(string) The name key of the dialog to remove from the registry
Note
This function is currently commented out in the codebase and not active
Documentation generated by AI on 2026-03-04

◆ RemoveIO()

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.

Parameters
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
Warning
This function raises w.Error() on failure and never returns in that case
-- Remove a MachMotion I/O (default device)
w.RemoveIO('ArmSecurity')
-- Remove I/O from a specific device
w.RemoveIO('Spindle3', 'SpindleFwd')
See also
WrapperModule.CreateIO() for creating dynamic I/O points
WrapperModule.RemoveRegister() for removing dynamic registers
Note
Documentation generated by AI on 2026-03-04

◆ RemoveRegister()

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.

Parameters
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
Warning
This function raises w.Error() on failure and never returns in that case
-- Remove a MachMotion register (default device)
w.RemoveRegister('ScreenState')
-- Remove a register from a specific device
w.RemoveRegister('MachMotion', 'DriftAmount')
See also
WrapperModule.CreateRegister() for creating dynamic registers
WrapperModule.RemoveIO() for removing dynamic I/O points
Note
Documentation generated by AI on 2026-03-04

◆ repr() [1/2]

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.

Parameters
tbl(table|nil) The table to format. Returns "nil" if tbl is nil
Returns
(string) A compact Lua-parsable string representation of the table (e.g., {1,2,["key"]="val"})
See also
WrapperModule.table.pretty.repr() for a human-readable indented version
WrapperModule.table.val_to_str() for the underlying value formatter
Note
Documentation generated by AI on 2026-03-04

◆ repr() [2/2]

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).

Parameters
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
Returns
(string) A human-readable, indented, Lua-parsable string representation of the table
See also
WrapperModule.table.repr() for the compact (non-indented) version
WrapperModule.table.pretty.val_to_str() for the underlying value formatter
Note
Documentation generated by AI on 2026-03-04

◆ request()

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.

Parameters
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
Returns
(string) The data read from the serial port
(number) The number of bytes actually read
Note
Documentation generated by AI on 2026-03-04

◆ requestBcc()

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.

Parameters
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
Returns
(string) The data read from the serial port
(number) The number of bytes actually read
Note
Documentation generated by AI on 2026-03-04

◆ RequestCycleStartHold()

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.

Returns
(boolean) True if the hold was newly activated, false if a hold was already active
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.ReleaseCycleStartHold() to release the hold
WrapperModule.IsCycleStartHoldActive() to check the current hold state
Note
Documentation generated by AI on 2026-03-04

◆ RequestData()

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.

Parameters
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)
Returns
(table|nil) The deserialized Lua table from the plugin response, or nil on error
(boolean) Success flag - true if the request completed successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ RequestMCodeHold()

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().

Returns
(number) The updated hold counter value after increment
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.ReleaseMCodeHold() to decrement the hold counter
WrapperModule.IsMCodeHoldActive() to check whether a hold is currently active
Note
Documentation generated by AI on 2026-03-04

◆ RequireParameterExist()

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.

Parameters
param(number) The Mach4 control parameter number to verify
inst(number|nil) The Mach4 instance handle. If not provided, uses current instance
Note
Documentation generated by AI on 2026-03-04

◆ ResetCycleStartPressedFlag()

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.

See also
WrapperModule.SetCycleStartPressedFlag() to activate the flag
WrapperModule.IsCycleStartPressedFlagSet() to read the current flag state
Note
Documentation generated by AI on 2026-03-04

◆ ResetGCodeCNTL1MST()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.SetGCodeCNTL1MST() to suppress M/S/T waits
WrapperModule.GetGCodeCNTL1MST() to read the current state
WrapperModule.GCodeCNTL1MSTToggle() to toggle the bit
Note
Documentation generated by AI on 2026-03-04

◆ RestoreInstance()

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.

Parameters
inst(number|nil) The instance to restore to, or nil to restore the previously stored instance
See also
WrapperModule.StoreInstance() for saving the current instance
WrapperModule.SetInstance() for directly setting the instance
Note
Documentation generated by AI on 2026-03-04

◆ Revert()

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.

Parameters
...(any) Values to pass through and return after reverting machine state
Returns
(...) All arguments passed to Revert(), allowing inline use in return statements
-- Basic usage
local saved_state = w.TemporaryMachineState("G20")
mc.mcCntlGcodeExecuteWait(inst, "G90 G53 G00 Z6")
saved_state:Revert()
-- Inline usage in a return statement
local saved_state = w.TemporaryMachineState("G21")
if rc ~= mc.MERROR_NOERROR then
return nil, saved_state:Revert(false), "Gcode Execute failed"
end
return true, saved_state:Revert(true), "Function Completed Successfully"
WrapperModule _TemporaryMachineState Revert()
Revert the machine state to the saved state and return any passed values.
See also
WrapperModule.TemporaryMachineState() to create a TemporaryMachineState object
Note
Documentation generated by AI on 2026-03-04

◆ RotateAroundPoint()

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).

Parameters
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
Returns
(table) Table with keys 'X' and 'Y' containing the rotated coordinates
(boolean) Success flag - false if any system variable retrieval fails
(string) Status message describing the result
See also
WrapperModule.GetRotatedPosition() for a simplified wrapper
WrapperModule.GetUnrotatedPosition() for the inverse transformation
Note
Documentation generated by AI on 2026-03-04

◆ Round()

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).

Parameters
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
Returns
(number) The rounded number
-- Round to nearest integer
local r = w.Round(3.5) -- Returns 4
-- Round to 2 decimal places
local r = w.Round(3.14159, 2) -- Returns 3.14
-- Round down to 1 decimal place
local r = w.Round(3.99, 1, -1) -- Returns 3.9
WrapperModule Round(num, idp, nearestupdown)
Round a number to a specified number of decimal places, with directional control.
Note
Documentation generated by AI on 2026-03-04

◆ RunBatchCode()

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.

Parameters
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
Warning
This function raises errors via w.Error() if the script file cannot be opened or if the exit code is non-zero
Note
Documentation generated by AI on 2026-03-04

◆ RunLuaString()

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.

Returns
a table containing the result of the expression or some error information if the couldn't couldn't be evaluated

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

Note
Documentation generated by AI on 2026-03-03

◆ RunUserCommand()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ RunUserCommandFromOperatorPanel()

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.

Parameters
command_name(string) The name of the user command to execute as an operator panel command
See also
WrapperModule.RunUserCommand() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ sample()

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').

Parameters
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')
Returns
(number|nil) The result of the summary operation, or nil if value_op is 'noop'
See also
WrapperModule.Averager:mean() for the default summary operation
WrapperModule.Averager:trend() for LSM regression-based smoothing
Note
Documentation generated by AI on 2026-03-04

◆ saveINI()

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.

Parameters
name(string) Full path to the INI file to write
t(table) Two-level table where t[section][key] = value
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SaveUserCommand()

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.

Parameters
command_table(table) The command configuration table to save. Must include a 'Name' field
See also
WrapperModule.GetUserCommandFilename() for the file path derivation
WrapperModule.ReadUserCommandFile() for reading saved command files
Note
Documentation generated by AI on 2026-03-04

◆ Scale()

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.

Parameters
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
Returns
(number|nil) The scaled output value, or nil if any parameter is not a number
(boolean) Success flag - true if scaling completed successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ SendGMSCommand()

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.

Parameters
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
Returns
(string|nil) The GMS command response, or nil if GMS is not present or on error
(boolean) Success flag - true if the command was sent successfully, false if GMS is absent or an error occurred
(string) Status message from w.RegSendCommand() or 'GMS_Not_Present' if GMS is absent
Note
Documentation generated by AI on 2026-03-04

◆ SendTableAcrossRegister()

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.

Parameters
luatable(table) The Lua table to serialize and store in the register
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No primary return value
(boolean) Success flag - true if the table was written successfully, false if register is busy
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.ReceiveTableAcrossRegister() to read and deserialize the table
WrapperModule.IsTableInRegister() to check register occupancy
Note
Documentation generated by AI on 2026-03-04

◆ SendZabbixData()

WrapperModule SendZabbixData ( data )

◆ SetAnalogOutput()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if the write completed successfully
(string) Status message describing the result
See also
WrapperModule.GetAnalogOutput() for reading the current analog output value
Note
Documentation generated by AI on 2026-03-04

◆ SetCache()

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.

Parameters
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
Returns
(any) The value that was stored
See also
WrapperModule.GetCache() for retrieving a stored value
WrapperModule.IsCached() for checking whether an entry exists
Note
Documentation generated by AI on 2026-03-04

◆ SetCommandButtonColors()

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.

Parameters
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")
Note
Documentation generated by AI on 2026-03-04

◆ SetCommandButtonLabels()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ SetCommandButtonTextColors()

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.

Parameters
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")
Note
Documentation generated by AI on 2026-03-04

◆ SetCommandFeedbackPeriod()

WrapperModule SetCommandFeedbackPeriod ( cmd_name ,
period_sec  )

◆ SetCommandTargetState()

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.

Parameters
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)
Note
Documentation generated by AI on 2026-03-04

◆ SetCurrentTool()

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.

Parameters
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
Returns
(number|nil) The tool number that was set, or 0/nil on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Raises an error via w.FunctionError() if ToolNumber is out of range
See also
WrapperModule.GetCurrentTool() to retrieve the current tool number
WrapperModule.SetPreviousTool() which is called to save the previous tool
Note
Documentation generated by AI on 2026-03-04

◆ SetCurrentToolPocket()

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.

Parameters
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
Returns
(number|nil) The pocket number that was set, or 0/nil on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
Returns an error via w.FunctionError() if pocket_number is out of range or ToolChangerMemorySource is not configured
See also
WrapperModule.GetCurrentToolPocket() to retrieve the current tool pocket
WrapperModule.SetPreviousToolPocket() which is called to save the previous pocket
Note
Documentation generated by AI on 2026-03-04

◆ SetCustomCntlDwellBarValue()

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.

Parameters
value(number) The dwell bar value to set, formatted to one decimal place
See also
WrapperModule.GetCustomCntlDwellBarValue() to read the current dwell bar value
WrapperModule.StartCustomCntlDwellBar() to start the dwell bar
WrapperModule.StopCustomCntlDwellBar() to stop the dwell bar
Note
Documentation generated by AI on 2026-03-04

◆ SetCycleStartPressedFlag()

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.

See also
WrapperModule.ResetCycleStartPressedFlag() to manually clear the flag
WrapperModule.UpdateCycleStartPressedFlag() to poll and auto-reset the flag
Note
Documentation generated by AI on 2026-03-04

◆ SetDriveEnable()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if the operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ SetDriveEnableAll()

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.

Parameters
val(boolean) The desired drive enable state: true to enable, false to disable
Returns
(nil) No primary return value
(boolean) Success flag - true if all instances were set successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ SetFeedrate()

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.

Parameters
feedrate(number|nil) The desired feedrate in units/minute. If nil or <= 0, uses existing cmd_feedrate
See also
WrapperModule.Jogger:CalculateFeedrate() for applying rapid override to the feedrate
Note
Documentation generated by AI on 2026-03-04

◆ SetFixtureSetterAutoName()

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.

Parameters
name(string) The name of the auto fixture setter to select
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name that was set
See also
WrapperModule.GetFixtureSetterAutoName() to read the current auto fixture setter selection
WrapperModule.GetAllAutoToolSetters() to retrieve all configured auto setters
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SetFixtureSetterManualName()

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.

Parameters
name(string) The name of the manual fixture setter to select
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name that was set
See also
WrapperModule.GetFixtureSetterManualName() to read the current manual fixture setter selection
WrapperModule.GetAllManualToolSetters() to retrieve all configured manual setters
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SetGCodeCNTL1MST()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
See also
WrapperModule.ResetGCodeCNTL1MST() to re-enable M/S/T waits
WrapperModule.GetGCodeCNTL1MST() to read the current state
WrapperModule.GCodeCNTL1MSTToggle() to toggle the bit
Note
Documentation generated by AI on 2026-03-04

◆ SetHardwareEnable()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if the operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ SetHardwareEnableAll()

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.

Parameters
val(boolean) The desired hardware enable state: true to enable, false to disable
Returns
(nil) No primary return value
(boolean) Success flag - true if all instances were set successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Note
Documentation generated by AI on 2026-03-04

◆ SetInstance()

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.

Parameters
instance(number) The Mach4 instance number to set as the active instance
See also
WrapperModule.SetInstanceToSelectedInstance() for setting to the selected instance
WrapperModule.StoreInstance() for saving the current instance before changing it
Note
Documentation generated by AI on 2026-03-04

◆ SetInstanceToSelectedInstance()

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.

See also
WrapperModule.SetInstance() for setting an explicit instance number
WrapperModule.GetSelectedInstance() for retrieving the selected instance
Note
Documentation generated by AI on 2026-03-04

◆ SetIoState()

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.

Parameters
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
Returns
(boolean|nil) The previous state of the I/O point, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetIoState() for reading the current I/O state
Note
Documentation generated by AI on 2026-03-04

◆ SetJogModeABS()

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.

See also
WrapperModule.Jogger:JogABS() for jogging to an absolute position
WrapperModule.Jogger:IsJogModeABS() to check if ABS mode is active
Note
Documentation generated by AI on 2026-03-04

◆ SetJogModeContinuous()

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.

See also
WrapperModule.Jogger:JogVelocity() for continuous velocity jogging
WrapperModule.Jogger:IsJogModeContinuous() to check if continuous mode is active
Note
Documentation generated by AI on 2026-03-04

◆ SetJogModeFeedrate()

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.

See also
WrapperModule.Jogger:JogRotaryFeedrate() for jogging in feedrate mode
WrapperModule.Jogger:IsJogModeFeedrate() to check if feedrate mode is active
Note
Documentation generated by AI on 2026-03-04

◆ SetJogModeIncremental()

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.

See also
WrapperModule.Jogger:JogIncremental() for performing incremental jog moves
WrapperModule.Jogger:IsJogModeIncremental() to check if incremental mode is active
Note
Documentation generated by AI on 2026-03-04

◆ SetMachEnable()

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.

Parameters
value(boolean) The desired enable state: true to enable, false to disable
Warning
This function modifies machine state for all instances simultaneously
Note
Documentation generated by AI on 2026-03-04

◆ SetMotorCountsPerUnitFromProfile()

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.

Parameters
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
See also
WrapperModule.GetMotorCountsPerUnitFromProfile() to read the current counts-per-unit value
Note
Documentation generated by AI on 2026-03-04

◆ SetMotorMaxAccelFromProfile()

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.

Parameters
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
See also
WrapperModule.GetMotorMaxAccelFromProfile() to read the current maximum acceleration
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ SetMotorMaxVelocityFromProfile()

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.

Parameters
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
See also
WrapperModule.GetMotorMaxVelocityFromProfile() to read the current maximum velocity
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ SetMotorSoftMaxLimitFromProfile()

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.

Parameters
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
See also
WrapperModule.GetMotorSoftMaxLimitFromProfile() to read the current soft maximum limit
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ SetMotorSoftMinLimitFromProfile()

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.

Parameters
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
See also
WrapperModule.GetMotorSoftMinLimitFromProfile() to read the current soft minimum limit
WrapperModule.GetMotorCountsPerUnitFromProfile() for the counts-per-unit conversion factor
Note
Documentation generated by AI on 2026-03-04

◆ SetNotificationBackgroundColour()

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().

Parameters
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)
See also
WrapperModule.CreateGMSNotification() for creating notifications
WrapperModule.UpdateNotification() for updating notification text
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamReg()

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.

Parameters
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
Returns
(number|nil) The value that was set, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamSig()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if the state was set successfully
(string) Status message describing the result
See also
WrapperModule.SetParamSig() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamValue()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetOEMParamValue() for reading the value back
WrapperModule.eSetOEMParamValue() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamValueBit()

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.

Parameters
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
Returns
(number|nil) The new parameter value after the bit operation, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.ClearOEMParamValueBit() for clearing a bit
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamValueBool()

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.

Parameters
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
Returns
(number|nil) The numeric value that was set (1 or 0), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetOEMParamValueBool() for reading the value back as a boolean
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMParamValueString()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValueString(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetOEMParamValueString() for reading the value back
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMRegValue()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetOEMRegValue() for reading the value back
WrapperModule.eSetOEMRegValue() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMRegValueBit()

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.

Parameters
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
Returns
(number|nil) The new register value after the bit operation, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.ClearOEMRegValueBit() for clearing a bit
Note
Documentation generated by AI on 2026-03-04

◆ SetOEMRegValueString()

WrapperModule SetOEMRegValueString ( RegName ,
val ,
inst  )

Set the value of a register to a string.

Parameters
RegNameThe name of the register to set.
valThe string value to set the register to.
instThe instance of the module (optional).
Returns
value, isok, msg

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.

Note
Documentation generated by AI on 2026-03-03 If any step fails, it returns an error message.

◆ SetParameter()

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().

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ SetParameterBit()

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.

Parameters
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
Note
Documentation generated by AI on 2026-03-04

◆ SetParamSig()

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:

  • Output or input signal: calls w.SetSignalState()
  • I/O point: calls w.SetIoState() Returns an error if the parameter is not mapped to a recognized signal or I/O type.
    Parameters
    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
    Returns
    (nil) No primary return value
    (boolean) Success flag - true if the state was set successfully
    (string) Status message describing the result
    Note
    Documentation generated by AI on 2026-03-04

◆ SetPreviousTool()

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.

Parameters
PreviousTool(number) The tool number to store as the previous tool
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetPreviousTool() to retrieve the stored previous tool number
WrapperModule.SetCurrentTool() which calls this function before updating the current tool
Note
Documentation generated by AI on 2026-03-04

◆ SetPreviousToolPocket()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetPreviousToolPocket() to retrieve the stored previous pocket number
WrapperModule.SetCurrentToolPocket() which calls this function before updating the current pocket
Note
Documentation generated by AI on 2026-03-04

◆ SetProbeFeedbackPositions()

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.

Parameters
positionnumber(number) The position slot index to write to (0 through 5 inclusive)
val(number) The position value to store in the OEM parameter
Warning
Raises a Lua error if positionnumber is not a number, is less than 0, or is greater than 5
See also
WrapperModule.GetProbeFeedbackPositions() to read a stored probe feedback position
WrapperModule.ClearProbeFeedbackPositions() to reset all probe feedback positions
Note
Documentation generated by AI on 2026-03-04

◆ SetRegValue()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValue(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetRegValue() for reading the value back
WrapperModule.eSetRegValue() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

◆ SetRegValueLong()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValueLong(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetRegValueLong() for reading the long integer value back
Note
Documentation generated by AI on 2026-03-04

◆ SetRegValueString()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcRegSetValueString(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetRegValueString() for reading the string value back
Note
Documentation generated by AI on 2026-03-04

◆ SetSelectedInstance()

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.

Parameters
inst(number) The Mach4 instance number to set as the selected instance
Note
Documentation generated by AI on 2026-03-04

◆ SetSelectedSpindle()

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.

Parameters
spindle(number) The spindle number to set as selected
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number) The spindle number that was set
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.GetSelectedSpindle() to retrieve the currently selected spindle
WrapperModule.GetDefaultSpindle() for the default spindle number
Note
Documentation generated by AI on 2026-03-04

◆ SetSelectedTool()

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.

Parameters
ToolNumber(number) The tool number to stage for the next tool change
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(number|nil) The tool number that was set, or 0 on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetSelectedTool() to retrieve the currently selected tool number
WrapperModule.SetCurrentTool() to mark a tool as actively loaded in the spindle
Note
Documentation generated by AI on 2026-03-04

◆ SetSignalEnable()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.SignalMap() for mapping a signal to an I/O point and enabling it
Note
Documentation generated by AI on 2026-03-04

◆ SetSignalState()

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.

Parameters
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
Returns
(number|nil) The return code from mc.mcSignalSetState(), or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.GetSignalState() for reading the current signal state
WrapperModule.eSetSignalState() for the error-raising variant
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SetSoftLimits()

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.

Parameters
OnOff(boolean) True to enable soft limits, false to disable
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetSoftLimits() to read the current soft limit state
Note
Documentation generated by AI on 2026-03-04

◆ SetStatus()

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.

Parameters
log_msg(string) The status message to display. Non-string values are converted via tostring()
Note
Documentation generated by AI on 2026-03-04

◆ SetStopStatus()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if the status was recorded successfully
(string) Status message from w.FunctionCompleted() or error description
See also
WrapperModule.CheckStopStatus() for comparing against the saved value
Note
Documentation generated by AI on 2026-03-04

◆ SetStopStatusAll()

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.

Returns
(nil) No meaningful primary return value
(boolean) Success flag - always true
(string) Status message from w.FunctionCompleted()
Note
Documentation generated by AI on 2026-03-04

◆ SetToolChangeStatus()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetToolChangeStatus() to read a tool change status attribute
Note
Documentation generated by AI on 2026-03-04

◆ SetToolSetterAutoName()

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.

Parameters
name(string) The name of the auto tool setter to select
Returns
(string) The name that was set
See also
WrapperModule.GetToolSetterAutoName() to read the current auto tool setter selection
WrapperModule.GetAllAutoToolSetters() to retrieve all configured auto setters
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SetToolSetterHeight()

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().

Parameters
ToolSetterName(string) The name of the tool setter whose height to set
Height(number) The height value to store for the tool setter
See also
WrapperModule.GetToolSetterHeight() to read the current tool setter height
WrapperModule.WriteToolSetter() for the underlying profile write operation
Note
Documentation generated by AI on 2026-03-04

◆ SetToolSetterManualName()

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.

Parameters
name(string) The name of the manual tool setter to select
inst(number) The Mach4 instance handle. If not provided, uses current instance
Returns
(string) The name that was set
See also
WrapperModule.GetToolSetterManualName() to read the current manual tool setter selection
WrapperModule.GetAllManualToolSetters() to retrieve all configured manual setters
Note
Documentation generated by AI on 2026-03-04

References name().

◆ SetToolSetterPosition() [1/2]

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().

Parameters
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
See also
WrapperModule.GetToolSetterPosition() to read the current tool setter Z position
WrapperModule.WriteToolSetter() for the underlying profile write operation
Note
Documentation generated by AI on 2026-03-04

◆ SetToolSetterPosition() [2/2]

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().

Parameters
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
See also
WrapperModule.GetToolSetterPosition() to read the current tool setter Z position
WrapperModule.WriteToolSetter() for the underlying profile write operation
Note
Documentation generated by AI on 2026-03-04

◆ SetToolTableUserValue()

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.

Parameters
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
Returns
(number|nil) The value that was set, or nil if tool number is 0
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetToolTableUserValue() to read a numeric user field value
WrapperModule.SetToolTableUserValueString() to write a string user field value
Note
Documentation generated by AI on 2026-03-04

◆ SetToolTableUserValue_Screen()

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).

Parameters
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()
Returns
(number|nil) The value that was set, or nil on error
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.SetToolTableUserValue() for the underlying implementation
Note
Documentation generated by AI on 2026-03-04

◆ SetToolTableUserValueString()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetToolTableUserValueString() to read a string user field value
WrapperModule.SetToolTableUserValue() to write a numeric user field value
Note
Documentation generated by AI on 2026-03-04

◆ SetValueBit()

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).

Parameters
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
Returns
(number|nil) The new value with the specified bit set or cleared, or nil on error
(boolean) Success flag - true if the operation completed successfully
(string) Status message describing the result
See also
WrapperModule.ClearValueBit() for clearing a bit
WrapperModule.GetValueBit() for reading a bit
Note
Documentation generated by AI on 2026-03-04

◆ SetVersionStrings()

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.

Parameters
_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 $")
Note
Documentation generated by AI on 2026-03-04

◆ SetWarningMessage()

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.

Parameters
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
Returns
(number|nil) The GMS notification handle, or nil on error
(boolean) Success flag - true if the notification was created successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.CreateGMSNotification() for the underlying notification creation
Note
Documentation generated by AI on 2026-03-04

◆ ShowNetworkAdapters()

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.

Note
Documentation generated by AI on 2026-03-04

◆ SignalMap()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if all mapping steps completed successfully
(string) Status message describing the result
See also
WrapperModule.SetSignalEnable() for enabling or disabling a signal without remapping
Note
Documentation generated by AI on 2026-03-04

◆ Sleep()

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:

  • Screen chunk: Yields to event loop via wx.wxYield() to prevent UI freezing
  • M-code chunk: Uses wx.wxMilliSleep() for blocking sleep The function automatically restores the original instance context on completion.
    Parameters
    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
    Returns
    (nil) No meaningful return value
    (boolean) Success flag - true if sleep completed, false if machine was disabled
    (string) Status message - "Complete" or error message
    Warning
    In screen chunks, this yields periodically. In M-code chunks, it blocks completely.
    Note
    The function checks machine disable status every sleep_per_iteration milliseconds unless IgnoreStopStatus is true
    -- Sleep for 2 seconds with machine monitoring
    local _, success, msg = w.Sleep(2000)
    if not success then
    w.AlarmError("Machine disabled during sleep")
    end
    -- Sleep without monitoring machine state
    w.Sleep(500, nil, true)
    WrapperModule Sleep(msTime, sleep_per_iteration, IgnoreStopStatus)
    Pause execution for specified milliseconds while monitoring machine state.
    Note
    Documentation generated by AI on 2026-03-03

◆ sortFunction()

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.

Parameters
a(any) First key to compare
b(any) Second key to compare
Returns
(boolean) True if the value associated with key a is less than the value associated with key b
Note
Documentation generated by AI on 2026-03-04

Referenced by GetKeysSortedByValue().

◆ SpindleSpeedVariation()

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.

Parameters
on_off(boolean) True to enable SSV, false to disable SSV
inst(number) The Mach4 instance handle. If not provided, uses current instance
-- Enable SSV (vary spindle +/-50 RPM with 3-second cycle, configured in params 1941/1942)
-- Disable SSV
CommonGUIModule Scheduler Enable()
Enable the scheduler and load the top scheduled file into Mach4.
WrapperModule SpindleSpeedVariation(on_off, inst)
Enable or disable Spindle Speed Variation (SSV).
See also
WrapperModule.SpindleSpeedVariationToggle() to toggle the current state
WrapperModule.IsSpindleSpeedVariationOn() to check the current state
Note
Documentation generated by AI on 2026-03-04

◆ SpindleSpeedVariationToggle()

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.

See also
WrapperModule.SpindleSpeedVariation() for enabling or disabling SSV directly
WrapperModule.IsSpindleSpeedVariationOn() for checking the current SSV state
Note
Documentation generated by AI on 2026-03-04

◆ split()

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).

Parameters
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
Returns
(table) An array of substrings resulting from splitting str on sSeparator
-- Split a comma-delimited string
local parts = w.string.split("a,b,c", ",")
-- parts = {"a", "b", "c"}
-- Split with maximum count
local parts = w.string.split("a:b:c:d", ":", 2)
-- parts = {"a", "b", "c:d"}
See also
http://lua-users.org/wiki/SplitJoin for the original implementation
Note
Documentation generated by AI on 2026-03-04

◆ SplitVersionString()

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.

Parameters
version_string(string) A period-or-comma-delimited version string (e.g., "4.2.0.4310")
Returns
(table) An array of version components, each either a number or a string if non-numeric
See also
WrapperModule.VerifyMinimumMachVersion() for the primary consumer of this function
Note
Documentation generated by AI on 2026-03-04

◆ SrcLoc()

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.

Returns
(string) The short source file path of the caller
(number) The current line number of the caller
See also
WrapperModule.GetCurrFileName() for the file name lookup
WrapperModule.GetCurrLineNo() for the line number lookup
Note
Documentation generated by AI on 2026-03-04

◆ StartCustomCntlDwellBar()

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.

Parameters
dwellbartable(table) Configuration table for the dwell bar (content depends on screen implementation)
See also
WrapperModule.StopCustomCntlDwellBar() to stop the dwell bar
WrapperModule.SetCustomCntlDwellBarValue() to update the dwell bar value during operation
Note
Documentation generated by AI on 2026-03-04

◆ stdev()

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.

Parameters
mean_value(number|nil) The mean of the sampled y-values. If nil, computed internally via variance()
Returns
(number) The standard deviation of the sampled y-values, or 0 if insufficient data
See also
WrapperModule.Averager:variance() for the underlying variance calculation
Note
Documentation generated by AI on 2026-03-04

◆ stdev_x()

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.

Parameters
mean_x(number|nil) The mean of the x-index sequence. If nil, computed internally via variance_x()
Returns
(number) The standard deviation of the x-index sequence
See also
WrapperModule.Averager:variance_x() for the underlying variance calculation
Note
Documentation generated by AI on 2026-03-04

◆ Stop()

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.

See also
WrapperModule.Jogger:IsJogging() to check jog state before stopping
WrapperModule.Jogger:StopWait() to stop and block until motion ceases
Note
Documentation generated by AI on 2026-03-04

◆ StopCustomCntlDwellBar()

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.

See also
WrapperModule.StartCustomCntlDwellBar() to start the dwell bar
WrapperModule.SetCustomCntlDwellBarValue() to update the dwell bar value during operation
Note
Documentation generated by AI on 2026-03-04

◆ StopWait()

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.

Warning
This function blocks execution until the axis stops moving
See also
WrapperModule.Jogger:Stop() for the stop initiation logic
WrapperModule.Jogger:Wait() for the blocking wait logic
Note
Documentation generated by AI on 2026-03-04

◆ StoreInstance()

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).

Returns
(number) The instance number that was stored
See also
WrapperModule.RestoreInstance() for restoring the saved instance
Note
Documentation generated by AI on 2026-03-04

◆ StringFormat()

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.

Parameters
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
Returns
(string) The assembled G-code string
(boolean) Success flag - always true
(string) Status message - "GCode string formatted"
-- Format a Z move command
local line, success, msg = w.StringFormat("G90 G00 Z", 2.5, "%0.4f", "(Safe Z)")
-- Result: line = "G90 G00 ZZ2.5000(Safe Z)"
Note
Documentation generated by AI on 2026-03-04

◆ StripGCodeLine()

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.

Parameters
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"})
Returns
(string|nil) The modified G-code line with specified keywords removed, or nil if arguments are invalid
(boolean) Success flag - true if completed successfully, false if Keyword or Line is nil
(string) Status message describing the result
(number) Total number of substitutions made across all keywords
Note
Documentation generated by AI on 2026-03-04

◆ StripModals()

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.

Parameters
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"})
Returns
(string) The modified G-code line with specified modals removed
(boolean) Success flag - true if completed successfully, false if invalid arguments
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-03
Returns
(string) Status message describing the result

◆ TableLength()

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.

Parameters
tbl(table) The table whose entries are to be counted
Returns
(number) The total number of key-value pairs in the table
Note
Documentation generated by AI on 2026-03-04

◆ TabletoCSV()

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.

Parameters
tt(table) Sequential array table of values to convert to CSV format
Returns
(string) The comma-separated CSV string representation of the table
Note
Documentation generated by AI on 2026-03-04

◆ TableToString()

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)".

Parameters
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
Returns
(string) String representation of the table
-- Basic table stringify
local s = w.TableToString({x=1, y=2})
-- Returns: "{\n [x] => 1, \n [y] => 2\n}"
-- Terse (compact) output
local s = w.TableToString({a=1, b=2}, nil, true)
-- Returns: "{ [a] => 1, [b] => 2}"
WrapperModule TableToString(tbl, indent, terse, linesep, depth, seen)
Convert a table to a human-readable string representation resembling JSON.
Note
Documentation generated by AI on 2026-03-04

◆ TemporaryMachineState()

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.

Parameters
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.
Returns
(table|nil) A TemporaryMachineState object with a Revert() method, or nil on error
(boolean) Success flag - true if the object was created and all actions succeeded
(string) Status message describing the result or w.FunctionError() on failure
-- Save state, switch to G20 (imperial), then restore
local saved_state, ok, msg = w.TemporaryMachineState("G20")
mc.mcCntlGcodeExecuteWait(inst, "G90 G53 G00 Z6")
saved_state:Revert()
-- Multiple actions
local saved_state, ok, msg = w.TemporaryMachineState({"G21", "G90"})
-- ... do work ...
saved_state:Revert()
UI Save()
Persist all tool setter configurations to the Mach4 profile.
See also
WrapperModule._TemporaryMachineState:Revert() to restore the saved machine state
Note
Documentation generated by AI on 2026-03-04

◆ TimeToMove()

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.

Parameters
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
Returns
(number|nil) The estimated travel time in milliseconds, or nil on error
(boolean) Success flag - true if the calculation completed successfully
(string) Status message from w.FunctionCompleted() or w.FunctionError()
See also
WrapperModule.GetProgrammedFeedRate() for the feed rate value used in the calculation
Note
Documentation generated by AI on 2026-03-04

◆ ToBoolean()

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:

  • number: false if 0, true if non-zero
  • string: matched case-insensitively against known boolean strings (see w.BooleanStrings); if no match, attempts tonumber() conversion and applies the number rule
  • nil: always false
  • anything else (tables, functions, etc.): true
    Parameters
    value(number|string|boolean|nil) The value to convert to boolean
    Returns
    (boolean) The boolean representation of the value
    See also
    WrapperModule.BooleanStrings for the full list of recognized string values
    Note
    Documentation generated by AI on 2026-03-04

◆ toint()

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:

  • If already an integer, returns unchanged
  • If a float, rounds to nearest integer (0.5 rounds up)
  • If a string, attempts numeric conversion then rounding
  • If unconvertible (e.g., table, function), returns nil
    Parameters
    number(number|string) The value to convert to an integer
    Returns
    (integer|nil) The converted integer value, or nil if conversion is not possible
    -- Convert float to integer
    local i = w.toint(3.7) -- Returns 4 (rounds up)
    -- Convert string to integer
    local i = w.toint("42") -- Returns 42
    -- Round to nearest
    local i = w.toint(2.4) -- Returns 2
    Note
    Documentation generated by AI on 2026-03-03

◆ tointeger()

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.

Parameters
tbl(table) An array of values to convert to integers
Returns
(table) A new array containing each element of tbl converted to an integer
Note
Documentation generated by AI on 2026-03-04

◆ tointstring()

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.

Parameters
number(number|string) The value to convert to an integer string
Returns
(string) String representation of the rounded integer value, or the original string if unparseable
Note
Documentation generated by AI on 2026-03-04

◆ tonumber()

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.

Parameters
number(number|string) The value to format and convert
format_number(number|nil) Number of decimal places (0-n). If nil, defaults to 6
Returns
(number|nil) The formatted number, or nil if input is nil
(boolean) Success flag - true if conversion completed successfully
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

References format_number().

◆ tostring() [1/2]

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.

Returns
(string) Multi-line string with the checkpoint name and all recorded checkpoint states in recency order
Note
Documentation generated by AI on 2026-03-04

◆ tostring() [2/2]

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.

Parameters
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
Returns
(string) Formatted string representation of the number
-- Format with default precision (6 decimals)
local str = w.tostring(3.14159265359) -- Returns "3.141593"
-- Format with custom precision
local str = w.tostring(2.5, 2) -- Returns "2.50"
-- Handle very small numbers (avoids scientific notation)
local str = w.tostring(0.0000001, 8) -- Returns "0.00000010"
Note
Documentation generated by AI on 2026-03-03

References format_number().

◆ trend()

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.

Returns
(number) The trend-line y-value at the most recent x position, or 0 if no data, or the mean on degenerate input
Note
Stores intermediate slope (B) and intercept (a) values on the Averager object as self.B and self.a
See also
WrapperModule.Averager:mean() for the simple arithmetic mean
Note
Documentation generated by AI on 2026-03-04

◆ UnMapMotorsFromAxis()

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.

Parameters
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
Returns
(nil) No primary return value
(boolean) Success flag - true if operation completed successfully
(string) Status message from w.FunctionCompleted()
See also
WrapperModule.MapMotorsToAxis() to map a motor to an axis
WrapperModule.GetAxisChildMotorID() to check which motors are mapped to an axis
Note
Documentation generated by AI on 2026-03-04

◆ update_recent()

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.

Parameters
id(any) The checkpoint identifier whose recency is being updated
Note
Documentation generated by AI on 2026-03-04

◆ UpdateCycleStartPressedFlag()

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.

See also
WrapperModule.SetCycleStartPressedFlag() to activate the flag
WrapperModule.ResetCycleStartPressedFlag() to deactivate the flag
Note
Documentation generated by AI on 2026-03-04

◆ UpdateFeedrate()

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.

See also
WrapperModule.Jogger:UseRapidOV() to enable rapid override mode
WrapperModule.Jogger:CalculateFeedrate() for the feedrate calculation logic
Note
Documentation generated by AI on 2026-03-04

◆ UpdateFunctionNameMap()

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().

Parameters
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
See also
WrapperModule.debug.AddToFunctionNameMap() for adding without clearing
WrapperModule.debug.GetFunctionName() for looking up names from the cache
Note
Documentation generated by AI on 2026-03-04

◆ UpdateGMSClass()

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.

Parameters
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"
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.GetGMSClassNumber() for converting class name strings to numbers
WrapperModule.UpdateGMSTitle() for updating the message title
Note
Documentation generated by AI on 2026-03-04

◆ UpdateGMSDescription()

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.

Parameters
Handle(number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage()
Text(string) The new description text to display in the message dialog
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.UpdateGMSTitle() for updating the title text
WrapperModule.UpdateGMSClass() for updating the message class
Note
Documentation generated by AI on 2026-03-04

◆ UpdateGMSTitle()

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.

Parameters
Handle(number|string) The GMS monitor handle returned by w.CreateSystemGlobalMessage()
Text(string) The new title text to display in the message dialog
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the command was sent successfully
(string) Status message from the GMS command response
See also
WrapperModule.UpdateGMSDescription() for updating the description text
WrapperModule.UpdateGMSClass() for updating the message class
Note
Documentation generated by AI on 2026-03-04

◆ UpdateNotification()

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.

Parameters
Identifier(number) The GMS notification handle returned by w.CreateGMSNotification() or w.CreateGMSDialog()
Text(string) The new text to display in the notification
See also
WrapperModule.CreateGMSNotification() for creating notifications
WrapperModule.SetNotificationBackgroundColour() for changing the notification background color
Note
Documentation generated by AI on 2026-03-04

◆ UpdatePleaseWaitDialog()

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.

Returns
(boolean) False if the condition is not yet met; otherwise closes the dialog and returns the close result
Warning
This is a closure defined inside WrapperModule._PleaseWaitDialog() and is only valid during that function's execution
See also
UI.ClosePleaseWaitDialog() which is called when a terminal condition is detected
WrapperModule.PleaseWaitType for the wait type constants used in the dispatch
Note
Documentation generated by AI on 2026-03-04

◆ UpdateRecentCSVs()

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().

Parameters
filename(string) The full path to the CSV file to add or promote in the recent files list
Note
Documentation generated by AI on 2026-03-04

◆ UpdateSelectedInstance()

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.

Returns
(number) The selected Mach4 instance number read from the register
See also
WrapperModule.GetSelectedInstance() for the cached read version
Note
Documentation generated by AI on 2026-03-04

◆ UpdateToolChangerInstance()

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.

See also
WrapperModule.GetToolChangerInstance() for the cached read version
Note
Documentation generated by AI on 2026-03-04

◆ UpdateWaitOnCondition()

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.

Returns
(number|boolean) 1 if condition met, -1 on error/disable, -10 on stop status change, -20 on timeout, or false if condition not yet satisfied
Warning
This is a closure and relies on upvalues from the enclosing _WaitOnCondition() scope
See also
WrapperModule.WaitOnCondition() for the public entry point
WrapperModule._WaitOnCondition() for the enclosing function that defines this closure
Note
Documentation generated by AI on 2026-03-04

◆ UseRapidOV()

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.

See also
WrapperModule.Jogger:CalculateFeedrate() for how rapid override affects feedrate
WrapperModule.Jogger:UpdateFeedrate() for dynamic feedrate adjustment during a jog
Note
Documentation generated by AI on 2026-03-04

◆ val_to_str() [1/2]

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().

Parameters
v(any) The value to convert to a string
Returns
(string) A Lua-parsable string representation of the value
See also
WrapperModule.table.repr() for the full compact table formatter
WrapperModule.table.key_to_str() for the key formatter
Note
Documentation generated by AI on 2026-03-04

◆ val_to_str() [2/2]

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.

Parameters
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
Returns
(string) The formatted string representation of the value
See also
WrapperModule.table.pretty.repr() for the full table formatter
WrapperModule.table.pretty.key_to_str() for the key formatter
Note
Documentation generated by AI on 2026-03-04

◆ variance()

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).

Parameters
mean_value(number|nil) The mean of the sampled y-values. If nil, computed via mean()
Returns
(number) The variance of the sampled y-values, or 0 if insufficient data
See also
WrapperModule.Averager:mean() for the mean calculation
WrapperModule.Averager:stdev() for the standard deviation
Note
Documentation generated by AI on 2026-03-04

◆ variance_x()

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).

Parameters
mean_x(number|nil) The mean of the x-index sequence. If nil, computed via mean_x()
Returns
(number) The variance of the x-index sequence, or 0 if insufficient data
See also
WrapperModule.Averager:mean_x() for the mean x calculation
Note
Documentation generated by AI on 2026-03-04

◆ VerifyAllAxesAreHomed()

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.

Parameters
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
Returns
(boolean|nil) True if all axes are homed, false if any are not homed, nil on error
(boolean) Success flag - true if the check completed (not necessarily that all are homed)
(string) Status message listing unhomed axes, or success/disabled message
See also
WrapperModule.IsAxisHomed() for per-axis homing status check
WrapperModule.VerifyAllAxesAreHomedCached() for a faster cached version
Note
Documentation generated by AI on 2026-03-04

◆ VerifyAllAxesAreHomedCached()

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.

Parameters
inst(number) The Mach4 instance handle. If not provided, uses current instance via w.GetUTI()
Returns
(boolean) True if all enabled axes are homed according to cached state, false otherwise
See also
WrapperModule.VerifyAllAxesAreHomed() for a full non-cached homing verification
WrapperModule.IsAxisHomed() for per-axis homing status
Note
Documentation generated by AI on 2026-03-04

◆ VerifyCacheExists()

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.

Parameters
category(string) The cache category name to verify or create
Returns
(table) The existing or newly created cache category table
See also
WrapperModule.SetCache() for storing values in the cache
WrapperModule.GetCache() for retrieving values from the cache
Note
Documentation generated by AI on 2026-03-04

◆ VerifyMinimumMachVersion()

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.

Parameters
version_string(string) The minimum required version as a period-delimited string (e.g., "4.2.0.4310")
Returns
(boolean) True if the running Mach4 version is greater than or equal to version_string, false otherwise
See also
WrapperModule.SplitVersionString() for the version string parsing logic
Note
Documentation generated by AI on 2026-03-04

◆ Wait()

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:

  • Screen chunk: Uses WaitOnCondition (with yielding) unless the jog is already stopping, in which case it falls back to a polling loop with w.Sleep(50) to avoid UI freezing.
  • M-code chunk: Uses a blocking repeat/until loop with w.Sleep(50). If w.Sleep() returns an error in either context, the jog is stopped and the error is returned. Also calls UpdateFeedrate() on each iteration if rapid override is active.
    Returns
    (nil) No meaningful return value on success
    (boolean) False on error (only returned in the polling loop path)
    (string) Error message if w.Sleep() fails
    Warning
    This function blocks execution and will freeze the UI if used improperly in a screen chunk
    See also
    WrapperModule.Jogger:JogStop() to stop the velocity jog
    WrapperModule.Jogger:UpdateFeedrate() for rapid override feedrate adjustment
    Note
    Documentation generated by AI on 2026-03-04

◆ WaitForFileQueueResponse()

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.

Parameters
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
Returns
(boolean) True if a reply was received, false if an error occurred (e.g., machine disabled)
(string) The reply string from the file queue, or an error message string
Warning
This function blocks execution until a reply is received or the machine is disabled
Note
Documentation generated by AI on 2026-03-04

◆ WaitForIoState()

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.

Parameters
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
Returns
(nil|boolean) nil on success, false if machine was disabled
(boolean) Success flag - true if state was reached, false on timeout, disable, or error
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
This function blocks execution in M-code chunk context
See also
WrapperModule.WaitForSignal() for waiting on signal state
WrapperModule.WaitForRegisterValue() for waiting on register value
Note
Documentation generated by AI on 2026-03-04

References AlarmMessage().

◆ WaitForOEMParamSig()

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.

Parameters
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
Returns
(nil|boolean) nil on success, false if machine was disabled
(boolean) Success flag - true if signal reached desired state, false on timeout, disable, or error
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
This function blocks execution in M-code chunk context
See also
WrapperModule.eWaitForOEMParamSig() for the error-raising equivalent
WrapperModule.WaitForSignal() for waiting on hardware signal state
Note
Documentation generated by AI on 2026-03-04

References AlarmMessage().

◆ WaitForRegisterValue()

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.

Parameters
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
Returns
(nil|boolean) nil on success, false if machine was disabled
(boolean) Success flag - true if value was reached, false on timeout, disable, or error
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
This function blocks execution in M-code chunk context
See also
WrapperModule.WaitForIoState() for waiting on I/O state
WrapperModule.WaitForSignal() for waiting on signal state
Note
Documentation generated by AI on 2026-03-04

References AlarmMessage().

◆ WaitForSignal()

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:

  • Screen chunk: Delegates to w.WaitOnCondition() with WaitType.Signal to avoid UI freezing
  • M-code chunk: Polls the signal state directly in a repeat loop with 2ms sleep intervals Constructs human-readable messages for timeout, wait, and disable conditions using signal info.
    Parameters
    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
    Returns
    (nil) No meaningful primary return value on success
    (boolean) Success flag - true if signal reached desired state, false on timeout or error
    (string) Status message from w.FunctionCompleted() or w.FunctionError()
    Warning
    This function blocks execution in M-code chunk context
    See also
    WrapperModule.WaitForIoState() for waiting on I/O state
    WrapperModule.WaitForOEMParamSig() for waiting on OEM parameter signal state
    Note
    Documentation generated by AI on 2026-03-04

References AlarmMessage().

◆ WaitOnCondition()

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.

Parameters
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)
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if condition was met, false if canceled, timed out, or errored
(string) Status message describing the outcome
Warning
This function blocks execution. It calls w.Sleep() internally and should not be used in screen chunks where UI responsiveness is required
See also
WrapperModule.PleaseWaitDialog() for the dialog-based equivalent
WrapperModule.WaitType for the available wait type constants
Note
Documentation generated by AI on 2026-03-04

◆ WaitOnCycleStart()

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.

Parameters
Message(string) The message to display to the operator while waiting
Returns
(boolean|nil) True on success, nil on error
(boolean) Success flag - true if cycle start was received
(string) Status message from w.FunctionCompleted() or w.FunctionError()
Warning
This function blocks execution until the operator presses Cycle Start
Note
Documentation generated by AI on 2026-03-04

◆ write()

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.

Parameters
stringdata(string) The string data to write to the serial port
timeout(number|nil) Timeout in milliseconds. If nil, defaults to 0 (non-blocking)
Returns
(string) The data string that was written
(number) The number of bytes actually written
Warning
Raises an error via w.Error() if the write fails
Note
Documentation generated by AI on 2026-03-04

◆ writeBcc()

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().

Parameters
stringdata(string) The data string to checksum and write
timeout(number|nil) Timeout in milliseconds for the write operation. If nil, defaults to 0
Returns
(string) The original data string (before checksum was appended)
(number) The number of bytes written to the port
Note
Documentation generated by AI on 2026-03-04

◆ WriteCommandFile()

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.

Note
Documentation generated by AI on 2026-03-04

◆ WriteCSV()

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).

Parameters
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"
Returns
(nil) No meaningful primary return value
(boolean) Success flag - always true
(string) Status message - " Ran Successfully"
Note
Documentation generated by AI on 2026-03-04

◆ WriteLines()

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()).

Parameters
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"
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if file was written successfully, false if file could not be opened
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ WriteTextFile()

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.

Parameters
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"
Returns
(nil) No meaningful primary return value
(boolean) Success flag - true if file was written successfully, false if file could not be opened
(string) Status message describing the result
Note
Documentation generated by AI on 2026-03-04

◆ WriteToGMSLog()

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().

Parameters
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"
Returns
(string|nil) The GMS command response, or nil on error
(boolean) Success flag - true if the log entry was written successfully
(string) Status message from the GMS command response
See also
WrapperModule.GetGMSClassNumber() for converting class name strings to numbers
WrapperModule.CreateGMSNotification() for displaying a visible notification
Note
Documentation generated by AI on 2026-03-04

◆ WriteToolSetter()

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.

Parameters
ini_table(table) The tool setter configuration table to write. Required keys:
  • SetterName (string): The tool setter name
  • SectionName (string): The INI profile section name (e.g., "ToolSetter0")
  • AutoSetter (boolean): Whether this is an auto setter
  • FixturesOffsets (boolean): Whether fixture offsets apply
  • FixtureOffsetMode (number): Fixture offset mode index
  • ProbeInput (number): Probe input index
  • DisableSoftlimits (boolean): Whether soft limits are disabled
  • Height (number): Tool setter height
  • ZPosition (number): Tool setter Z position
  • GoToPosition (string): GoTo position name before touchoff
  • EndGoToPosition (string): GoTo position name after touchoff
Returns
(table) The ini_table passed in, after writing
See also
WrapperModule.GetAllToolSetters() to read tool setter configurations
WrapperModule.CreateToolSetter() to create a new tool setter
Note
Documentation generated by AI on 2026-03-04

◆ wxMessageBox()

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.

Parameters
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)
Returns
(number) The wx message box result code (e.g., wx.wxOK, wx.wxCANCEL, wx.wxYES, wx.wxNO)
Note
Documentation generated by AI on 2026-03-04

◆ Yield()

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.

Parameters
yield_events(number|nil) Number of yield iterations to perform. If nil, defaults to 1
Returns
(nil) No meaningful primary return value
(boolean) Success flag - always true
(string) Status message - "Complete"
Note
This function temporarily switches the active instance and ensures it is restored on completion
See also
WrapperModule.Sleep() for a time-based blocking wait with machine disable monitoring
Note
Documentation generated by AI on 2026-03-04