Difference between revisions of "Lua:Class:Thread"

From Cheat Engine
Jump to navigation Jump to search
(Created page with 'Category:Lua Thread '''class''': ('''Inheritance''': ''Object'') The thread class executes the given function in another thread using the systems thread…')
 
m
 
(2 intermediate revisions by 2 users not shown)
Line 2: Line 2:
 
Thread '''class''': ('''Inheritance''': ''[[Lua:Class:Object|Object]]'')
 
Thread '''class''': ('''Inheritance''': ''[[Lua:Class:Object|Object]]'')
  
The thread class executes the given function in another thread using the systems thread mechanism
+
The Thread class represents a system thread in Cheat Engine, allowing you to execute Lua code concurrently. 
 +
Threads can be created using [[createThread]], [[createThreadSuspended]], or [[createThreadNewState]].
  
 +
== Creation Functions ==
 +
* '''createThread(function(Thread, ...), ...)''' 
 +
** Executes the given function in a new thread. Returns a Thread object. 
 +
** The function declaration should be: <code>function(Thread, ...)</code>
  
== Creation ==
+
* '''createThreadSuspended(function(Thread, ...), ...)''
; [[Lua:createThread|createThread]](''function(Thread,...)'', ...)
+
** Same as <code>createThread</code>, but the thread will not run until <code>resume()</code> is called.
: returns the Thread class object
+
 
 +
* '''createThreadNewState(scripttext)''' 
 +
** Creates a new thread in a new Lua state.
 +
** This is more efficient (no Lua locking), but has no access to user-defined Lua functions and only limited base CE functions.
 +
** The script is called inside <code>function(t)</code> where <code>t</code> is the thread object. 
 +
** Watch for <code>t.Terminated</code> to quit. 
 +
** '''Note:''' Unlike <code>createThread</code>, the created thread does not <code>freeOnTerminate</code> by default, so you can read the <code>Result</code> property after the thread finishes.
  
 
== Properties ==
 
== Properties ==
; Name &#58; string
+
{| class="wikitable" style="width:100%"
: This name will be shown when the thread terminated abnormally
+
! Property
 
+
! Type
; Finished &#58; boolean
+
! Description
: ''true'' if the thread has reached the end. Do not rely on this if the thread is freeOnTerminate(true) (which is the default)
+
|-
 
+
| Name
; Terminated &#58; function(timer)
+
| String
: ''true'' if the Terminate method has been called
+
| The name of the thread (shown if the thread terminates abnormally).
 +
|-
 +
| Finished
 +
| Boolean
 +
| True if the thread has reached the end. Do not rely on this if <code>freeOnTerminate(true)</code> is set (default is true).
 +
|-
 +
| Terminated
 +
| Boolean
 +
| True if the <code>terminate()</code> method has been called.
 +
|-
 +
| Result
 +
| String
 +
| The result of the thread function as a string.
 +
|}
  
 
== Methods ==
 
== Methods ==
 +
{| class="wikitable" style="width:100%"
 +
! Method
 +
! Parameters
 +
! Returns
 +
! Description
 +
|-
 +
| freeOnTerminate
 +
| Boolean (state)
 +
| None
 +
| When set to true, the thread object will free itself when the function ends (default = true). 
 +
Note: Use only from inside the thread function.
 +
|-
 +
| synchronize
 +
| function(thread, ...), ...
 +
| Any
 +
| Called from inside the thread. Causes the main thread to execute the given function and waits for it to finish. 
 +
Usually used for GUI access. Returns the return value of the function.
 +
|-
 +
| waitfor
 +
| None
 +
| None
 +
| Waits for the thread to finish. (Not recommended to call from inside the thread itself.)
 +
|-
 +
| suspend
 +
| None
 +
| None
 +
| Suspends the thread's execution.
 +
|-
 +
| resume
 +
| None
 +
| None
 +
| Resumes the thread's execution.
 +
|-
 +
| terminate
 +
| None
 +
| None
 +
| Tells the thread it should terminate. The <code>Terminated</code> property will become true.
 +
|}
  
; freeOnTerminate(''state'') &#58;
+
== Examples ==
: When set to true the thread object will free itself when the function ends (default=true)
+
<pre>
; Note: Use this only from inside the thread function as the thread might have already terminated and freed itself when called
+
-- Table to hold thread objects
 +
local threads = {}
 +
local threadCount = 5
  
; synchronize(''function(thread,...)'', ...) : given function's return value
+
-- Function executed by each thread
: Usually for GUI access. Called from inside the thread
+
local function threadFunc(thread, number)
; This will cause the thread to get the main thread to execute the given function and wait for it to finish.
+
  print("Thread " .. number .. " started")
; Returns the return value of the given function
+
  -- Loop until the thread is terminated
 +
  while not thread.Terminated do
 +
    sleep(500) -- Simulate work
 +
  end
 +
  print("Thread " .. number .. " terminated")
 +
end
  
; waitfor() &#58;
+
-- Create and start the threads
: Waits for the given thread to finish (Not recommended to call this from inside the thread itself)
+
for i = 1, threadCount do
 +
  threads[i] = createThread(function(thread) threadFunc(thread, i) end)
 +
end
  
; suspend()
+
-- Timer to automatically terminate all threads after 5 seconds
: Suspend the thread's execution
+
local terminateTimer = createTimer()
 
+
terminateTimer.Interval = 5000
; resume() &#58;
+
terminateTimer.OnTimer = function(timer)
: Resume the thread;s executionmm
+
  for i = 1, threadCount do
 
+
     if threads[i] and not threads[i].Terminated then
; terminate()
+
       threads[i]:terminate()
: Tells the thread it should terminate. The Terminated property will become true
 
 
 
== Examples ==
 
  local thread = createThread(function(timer)
 
    local i = 0
 
     while i < 100 do
 
      i = i + 1
 
       print(i)
 
      sleep(100)
 
 
     end
 
     end
    return 50
+
  end
   end)
+
   terminateTimer.destroy() -- Stop the timer after terminating threads
 +
end
  
  -- run given function after a delay
+
-- Timer to terminate all threads if ESC is pressed
  local function delayed(func, delay)
+
local escTimer = createTimer()
    if type(func) ~= 'function' then return end
+
escTimer.Interval = 100
    if type(delay) ~= 'number' then delay = 1000 end
+
escTimer.OnTimer = function(timer)
     local t = createTimer()
+
  if isKeyPressed(VK_ESCAPE) then
     t.Interval = delay
+
     print("ESC pressed, terminating all threads.")
    t.OnTimer = function(t)
+
     for i = 1, threadCount do
      -- only run once by destroying the timer object
+
      if threads[i] and not threads[i].Terminated then
      t.destroy()
+
        threads[i]:terminate()
       func()
+
       end
 
     end
 
     end
 +
    escTimer .destroy() -- Stop the timer after handling ESC
 
   end
 
   end
 
+
end
  delayed(function()
+
</pre>
    print('suspending')
 
    thread.suspend()
 
    delayed(function()
 
      print('resuming')
 
      thread.resume()
 
    end, 3500)
 
  end, 5000)
 
  
 
{{LuaSeeAlso}}
 
{{LuaSeeAlso}}
Line 79: Line 136:
 
=== Related Functions ===
 
=== Related Functions ===
 
* [[Lua:createThreadSuspended|createThreadSuspended]]
 
* [[Lua:createThreadSuspended|createThreadSuspended]]
 +
* [[Lua:createThreadNewState|createThreadNewState]]
 +
* [[createTimer]]
 +
* [[isKeyPressed]]

Latest revision as of 19:35, 11 July 2025

Thread class: (Inheritance: Object)

The Thread class represents a system thread in Cheat Engine, allowing you to execute Lua code concurrently. Threads can be created using createThread, createThreadSuspended, or createThreadNewState.

Creation Functions[edit]

  • createThread(function(Thread, ...), ...)
    • Executes the given function in a new thread. Returns a Thread object.
    • The function declaration should be: function(Thread, ...)
  • createThreadSuspended(function(Thread, ...), ...)
    • Same as createThread, but the thread will not run until resume() is called.
  • createThreadNewState(scripttext)
    • Creates a new thread in a new Lua state.
    • This is more efficient (no Lua locking), but has no access to user-defined Lua functions and only limited base CE functions.
    • The script is called inside function(t) where t is the thread object.
    • Watch for t.Terminated to quit.
    • Note: Unlike createThread, the created thread does not freeOnTerminate by default, so you can read the Result property after the thread finishes.

Properties[edit]

Property Type Description
Name String The name of the thread (shown if the thread terminates abnormally).
Finished Boolean True if the thread has reached the end. Do not rely on this if freeOnTerminate(true) is set (default is true).
Terminated Boolean True if the terminate() method has been called.
Result String The result of the thread function as a string.

Methods[edit]

Method Parameters Returns Description
freeOnTerminate Boolean (state) None When set to true, the thread object will free itself when the function ends (default = true).

Note: Use only from inside the thread function.

synchronize function(thread, ...), ... Any Called from inside the thread. Causes the main thread to execute the given function and waits for it to finish.

Usually used for GUI access. Returns the return value of the function.

waitfor None None Waits for the thread to finish. (Not recommended to call from inside the thread itself.)
suspend None None Suspends the thread's execution.
resume None None Resumes the thread's execution.
terminate None None Tells the thread it should terminate. The Terminated property will become true.

Examples[edit]

-- Table to hold thread objects
local threads = {}
local threadCount = 5

-- Function executed by each thread
local function threadFunc(thread, number)
  print("Thread " .. number .. " started")
  -- Loop until the thread is terminated
  while not thread.Terminated do
    sleep(500) -- Simulate work
  end
  print("Thread " .. number .. " terminated")
end

-- Create and start the threads
for i = 1, threadCount do
  threads[i] = createThread(function(thread) threadFunc(thread, i) end)
end

-- Timer to automatically terminate all threads after 5 seconds
local terminateTimer = createTimer()
terminateTimer.Interval = 5000
terminateTimer.OnTimer = function(timer)
  for i = 1, threadCount do
    if threads[i] and not threads[i].Terminated then
      threads[i]:terminate()
    end
  end
  terminateTimer.destroy() -- Stop the timer after terminating threads
end

-- Timer to terminate all threads if ESC is pressed
local escTimer = createTimer()
escTimer.Interval = 100
escTimer.OnTimer = function(timer)
  if isKeyPressed(VK_ESCAPE) then
    print("ESC pressed, terminating all threads.")
    for i = 1, threadCount do
      if threads[i] and not threads[i].Terminated then
        threads[i]:terminate()
      end
    end
    escTimer .destroy() -- Stop the timer after handling ESC
  end
end

See also[edit]

Related Functions[edit]