Difference between revisions of "Lua:Class:Thread"

From Cheat Engine
Jump to navigation Jump to search
m
(Major overhaul of the post.)
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 
[[Category:Lua]]
 
[[Category:Lua]]
Thread '''class''': ('''Inheritance''': ''[[Lua:Class:Object|Object]]'')
+
{{Class|'''class''' Thread ''':''' Object}}
  
The Thread class represents a system thread in Cheat Engine, allowing you to execute Lua code concurrently. 
+
The Thread class represents a Lua thread object.
Threads can be created using [[createThread]], [[createThreadSuspended]], or [[createThreadNewState]].
 
  
== Creation Functions ==
+
A Thread inherits from Object. It can execute a function in another system thread, start suspended, synchronize code with the main thread, and be asked to terminate.
* '''createThread(function(Thread, ...), ...)''' 
 
** Executes the given function in a new thread. Returns a Thread object. 
 
** The function declaration should be: <code>function(Thread, ...)</code>
 
  
* '''createThreadSuspended(function(Thread, ...), ...)'''
+
===Inheritance===
** Same as <code>createThread</code>, but the thread will not run until <code>resume()</code> is called.
+
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 +
!align="left"|Class
 +
!align="left"|Inherits From
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|Thread
 +
|Object
 +
|Executes Lua code in another system thread.
 +
|}
 +
 
 +
===Creation===
 +
{{CodeBox|'''function''' createThread(''function'', ''...'') ''':''' Thread}}
 +
{{CodeBox|'''function''' createThreadSuspended(''function'', ''...'') ''':''' Thread}}
 +
{{CodeBox|'''function''' createThreadNewState(''scripttext'') ''':''' Thread}}
 +
 
 +
Creates a Thread object.
 +
 
 +
createThread executes the given function in another thread using the system thread mechanism. The function receives the Thread object as its first parameter, followed by any additional arguments.
 +
 
 +
createThreadSuspended creates a thread in a suspended state. It will not run until resume() is called.
 +
 
 +
createThreadNewState creates a new thread in a new Lua state. This is more efficient because no locking inside Lua takes place, but the thread has no access to user-defined Lua functions and only limited base Cheat Engine functions. The script is called inside a function(t), where t is the Thread object. Watch t.Terminated to know when to quit.
 +
 
 +
Unlike createThread, a thread created with createThreadNewState does not free itself on terminate by default, so the Result property can be read after the thread has finished.
 +
 
 +
===Function Parameters===
 +
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
 +
!align="left"|Function
 +
!align="left"|Parameter
 +
!style="width: 80%;background-color:white;" align="left"|Description
 +
|-
 +
|createThread(function, ...)
 +
|function
 +
|The function to execute in another thread. The function receives the Thread object as the first parameter.
 +
|-
 +
|createThread(function, ...)
 +
|...
 +
|Optional additional arguments passed to the thread function.
 +
|-
 +
|createThreadSuspended(function, ...)
 +
|function
 +
|The function to execute once the suspended thread is resumed. The function receives the Thread object as the first parameter.
 +
|-
 +
|createThreadSuspended(function, ...)
 +
|...
 +
|Optional additional arguments passed to the thread function.
 +
|-
 +
|createThreadNewState(scripttext)
 +
|scripttext
 +
|The Lua script text to execute in a new Lua state.
 +
|}
 +
 
 +
===Returns===
 +
Thread — The created Thread object.
  
* '''createThreadNewState(scripttext)''' 
+
===Thread Function Signature===
** Creates a new thread in a new Lua state. 
+
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
** This is more efficient (no Lua locking), but has no access to user-defined Lua functions and only limited base CE functions. 
+
!align="left"|Function Signature
** The script is called inside <code>function(t)</code> where <code>t</code> is the thread object.
+
!style="width: 80%;background-color:white;" align="left"|Description
** 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.
+
|function(thread, ...)
 +
|The thread function receives the Thread object as the first parameter, followed by any additional arguments passed to createThread or createThreadSuspended.
 +
|}
  
== Properties ==
+
===Properties===
{| class="wikitable" style="width:100%"
+
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
! Property
+
!align="left"|Property
! Type
+
!align="left"|Type
! Description
+
!style="width: 80%;background-color:white;" align="left"|Description
 
|-
 
|-
| Name
+
|Name
| String
+
|String
| The name of the thread (shown if the thread terminates abnormally).
+
|The thread name. This name is shown when the thread terminates abnormally.
 
|-
 
|-
| Finished
+
|Finished
| Boolean
+
|Boolean
| True if the thread has reached the end. Do not rely on this if <code>freeOnTerminate(true)</code> is set (default is true).
+
|Returns true if the thread has reached the end. Do not rely on this if freeOnTerminate(true) is used, which is the default.
 
|-
 
|-
| Terminated
+
|Terminated
| Boolean
+
|Boolean
| True if the <code>terminate()</code> method has been called.
+
|Returns true if terminate() has been called.
 
|-
 
|-
| Result
+
|Result
| String
+
|String
| The result of the thread function as a string.
+
|The result of the thread function as a string.
 
|}
 
|}
  
== Methods ==
+
===Methods===
{| class="wikitable" style="width:100%"
+
{|width="85%" cellpadding="10%" cellspacing="0" border="0"
! Method
+
!align="left"|Method
! Parameters
+
!align="left"|Return Type
! Returns
+
!style="width: 80%;background-color:white;" align="left"|Description
! Description
 
 
|-
 
|-
| freeOnTerminate
+
|freeOnTerminate(state)
| Boolean (state)
+
|void
| None
+
|When set to true, the Thread object frees itself when the function ends. The default is true. Use this only from inside the thread function, because the thread may already have terminated and freed itself when called from outside.
| 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
+
|synchronize(function(thread, ...), ...)
| function(thread, ...), ...
+
|Any
| Any
+
|Called from inside the thread. Executes the given function in the main thread and waits for it to finish. Usually used for GUI access. Returns the return value of the given function.
| 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
+
|waitfor()
| None
+
|void
| None
+
|Waits for the thread to finish. It is not recommended to call this from inside the thread itself.
| Waits for the thread to finish. (Not recommended to call from inside the thread itself.)
 
 
|-
 
|-
| suspend
+
|suspend()
| None
+
|void
| None
+
|Suspends the thread's execution.
| Suspends the thread's execution.
 
 
|-
 
|-
| resume
+
|resume()
| None
+
|void
| None
+
|Resumes the thread's execution.
| Resumes the thread's execution.
 
 
|-
 
|-
| terminate
+
|terminate()
| None
+
|void
| None
+
|Tells the thread it should terminate. The Terminated property becomes true.
| Tells the thread it should terminate. The <code>Terminated</code> property will become true.
 
 
|}
 
|}
  
== Examples ==
+
===Examples===
 +
<pre>
 +
local thread = createThread(function(thread)
 +
  thread.Name = "Example Thread"
 +
 
 +
  for i = 1, 5 do
 +
    if thread.Terminated then
 +
      return
 +
    end
 +
 
 +
    print("Thread step: " .. tostring(i))
 +
    sleep(500)
 +
  end
 +
end)
 +
</pre>
 +
 
 
<pre>
 
<pre>
-- Table to hold thread objects
+
local thread = createThread(function(thread, message, count)
local threads = {}
+
  for i = 1, count do
local threadCount = 5
+
    if thread.Terminated then
 +
      return
 +
    end
 +
 
 +
    print(message .. " " .. tostring(i))
 +
    sleep(500)
 +
  end
 +
end, "Tick", 5)
 +
</pre>
 +
 
 +
<pre>
 +
local thread = createThreadSuspended(function(thread)
 +
  print("This runs after resume()")
 +
end)
 +
 
 +
thread.resume()
 +
</pre>
 +
 
 +
<pre>
 +
local form = createForm()
 +
local label = createLabel(form)
 +
 
 +
label.Parent = form
 +
label.Caption = "Waiting..."
 +
form.show()
 +
 
 +
createThread(function(thread)
 +
  sleep(1000)
 +
 
 +
  thread.synchronize(function(thread)
 +
    label.Caption = "Updated from the main thread"
 +
  end)
 +
end)
 +
</pre>
 +
 
 +
<pre>
 +
local thread = createThread(function(thread)
 +
  thread.freeOnTerminate(false)
 +
 
 +
  local count = 0
  
-- 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
 
   while not thread.Terminated do
     sleep(500) -- Simulate work
+
    count = count + 1
 +
     sleep(500)
 
   end
 
   end
  print("Thread " .. number .. " terminated")
 
end
 
  
-- Create and start the threads
+
   return tostring(count)
for i = 1, threadCount do
+
end)
   threads[i] = createThread(function(thread) threadFunc(thread, i) end)
 
end
 
  
-- Timer to automatically terminate all threads after 5 seconds
+
sleep(2000)
local terminateTimer = createTimer()
+
thread.terminate()
terminateTimer.Interval = 5000
+
thread.waitfor()
terminateTimer.OnTimer = function(timer)
+
 
   for i = 1, threadCount do
+
print("Thread result: " .. tostring(thread.Result))
     if threads[i] and not threads[i].Terminated then
+
 
       threads[i]:terminate()
+
thread.destroy()
 +
</pre>
 +
 
 +
<pre>
 +
local thread = createThreadNewState([[
 +
  local count = 0
 +
 
 +
   while not t.Terminated do
 +
    count = count + 1
 +
    sleep(500)
 +
 
 +
     if count >= 5 then
 +
       break
 
     end
 
     end
 
   end
 
   end
  timer.destroy() -- Stop the timer after terminating threads
 
end
 
  
-- Timer to terminate all threads if ESC is pressed
+
  return tostring(count)
local escTimer = createTimer()
+
]])
escTimer.Interval = 100
+
 
escTimer.OnTimer = function(timer)
+
thread.waitfor()
  if isKeyPressed(VK_ESCAPE) then
+
 
    print("ESC pressed, terminating all threads.")
+
print("Result: " .. tostring(thread.Result))
    for i = 1, threadCount do
+
 
      if threads[i] and not threads[i].Terminated then
+
thread.destroy()
        threads[i]:terminate()
 
      end
 
    end
 
    timer.destroy() -- Stop the timer after handling ESC
 
  end
 
end
 
 
</pre>
 
</pre>
  
 
{{LuaSeeAlso}}
 
{{LuaSeeAlso}}
 
=== Related Functions ===
 
* [[Lua:createThreadSuspended|createThreadSuspended]]
 
* [[Lua:createThreadNewState|createThreadNewState]]
 
* [[createTimer]]
 
* [[isKeyPressed]]
 

Latest revision as of 19:46, 23 June 2026

{} Class

class Thread : Object

The Thread class represents a Lua thread object.

A Thread inherits from Object. It can execute a function in another system thread, start suspended, synchronize code with the main thread, and be asked to terminate.

Inheritance[edit]

Class Inherits From Description
Thread Object Executes Lua code in another system thread.

Creation[edit]

<> Lua API Reference

function createThread(function, ...) : Thread

<> Lua API Reference

function createThreadSuspended(function, ...) : Thread

<> Lua API Reference

function createThreadNewState(scripttext) : Thread

Creates a Thread object.

createThread executes the given function in another thread using the system thread mechanism. The function receives the Thread object as its first parameter, followed by any additional arguments.

createThreadSuspended creates a thread in a suspended state. It will not run until resume() is called.

createThreadNewState creates a new thread in a new Lua state. This is more efficient because no locking inside Lua takes place, but the thread has no access to user-defined Lua functions and only limited base Cheat Engine functions. The script is called inside a function(t), where t is the Thread object. Watch t.Terminated to know when to quit.

Unlike createThread, a thread created with createThreadNewState does not free itself on terminate by default, so the Result property can be read after the thread has finished.

Function Parameters[edit]

Function Parameter Description
createThread(function, ...) function The function to execute in another thread. The function receives the Thread object as the first parameter.
createThread(function, ...) ... Optional additional arguments passed to the thread function.
createThreadSuspended(function, ...) function The function to execute once the suspended thread is resumed. The function receives the Thread object as the first parameter.
createThreadSuspended(function, ...) ... Optional additional arguments passed to the thread function.
createThreadNewState(scripttext) scripttext The Lua script text to execute in a new Lua state.

Returns[edit]

Thread — The created Thread object.

Thread Function Signature[edit]

Function Signature Description
function(thread, ...) The thread function receives the Thread object as the first parameter, followed by any additional arguments passed to createThread or createThreadSuspended.

Properties[edit]

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

Methods[edit]

Method Return Type Description
freeOnTerminate(state) void When set to true, the Thread object frees itself when the function ends. The default is true. Use this only from inside the thread function, because the thread may already have terminated and freed itself when called from outside.
synchronize(function(thread, ...), ...) Any Called from inside the thread. Executes the given function in the main thread and waits for it to finish. Usually used for GUI access. Returns the return value of the given function.
waitfor() void Waits for the thread to finish. It is not recommended to call this from inside the thread itself.
suspend() void Suspends the thread's execution.
resume() void Resumes the thread's execution.
terminate() void Tells the thread it should terminate. The Terminated property becomes true.

Examples[edit]

local thread = createThread(function(thread)
  thread.Name = "Example Thread"

  for i = 1, 5 do
    if thread.Terminated then
      return
    end

    print("Thread step: " .. tostring(i))
    sleep(500)
  end
end)
local thread = createThread(function(thread, message, count)
  for i = 1, count do
    if thread.Terminated then
      return
    end

    print(message .. " " .. tostring(i))
    sleep(500)
  end
end, "Tick", 5)
local thread = createThreadSuspended(function(thread)
  print("This runs after resume()")
end)

thread.resume()
local form = createForm()
local label = createLabel(form)

label.Parent = form
label.Caption = "Waiting..."
form.show()

createThread(function(thread)
  sleep(1000)

  thread.synchronize(function(thread)
    label.Caption = "Updated from the main thread"
  end)
end)
local thread = createThread(function(thread)
  thread.freeOnTerminate(false)

  local count = 0

  while not thread.Terminated do
    count = count + 1
    sleep(500)
  end

  return tostring(count)
end)

sleep(2000)
thread.terminate()
thread.waitfor()

print("Thread result: " .. tostring(thread.Result))

thread.destroy()
local thread = createThreadNewState([[
  local count = 0

  while not t.Terminated do
    count = count + 1
    sleep(500)

    if count >= 5 then
      break
    end
  end

  return tostring(count)
]])

thread.waitfor()

print("Result: " .. tostring(thread.Result))

thread.destroy()

Main Pages

Core Lua documentation entry points

Lua
Script Engine