Lua:createThread
Jump to navigation
Jump to search
Executes the given function in another thread using the system's thread mechanism.
The function returns a Thread class object. The thread function receives the Thread object as its first parameter, followed by any additional parameters passed to createThread.
Contents
- 1 Function Declaration
- 2 Function Parameters
- 3 Returns
- 4 Examples
- 4.1 Create a basic thread
- 4.2 Use the Thread parameter
- 4.3 Pass arguments to the thread function
- 4.4 Run repeated work in a thread
- 4.5 Use synchronize for main-thread work
- 4.6 Create a thread from a named function
- 4.7 Pass multiple values
- 4.8 Store the returned Thread object
- 4.9 Guard thread creation behind a condition
Function Declaration[edit]
1 function(thread, ...)
Function Parameters[edit]
| Parameter | Type | Description |
|---|---|---|
| function | Function | The function to execute in the new thread. It receives the Thread object as its first argument. |
| ... | Any OPTIONAL | Optional arguments that are passed to the thread function after the Thread object. |
Returns[edit]
Thread — The created Thread object.
Examples[edit]
Create a basic thread[edit]
1 local thread = createThread(function(thread)
2 print("Thread started")
3 end)
Use the Thread parameter[edit]
1 local thread = createThread(function(thread)
2 print("Thread object: " .. tostring(thread))
3 end)
Pass arguments to the thread function[edit]
1 local text = "Hello from another thread"
2 local count = 3
3
4 local thread = createThread(function(thread, message, repetitions)
5 for i = 1, repetitions do
6 print(message .. " #" .. tostring(i))
7 end
8 end, text, count)
Run repeated work in a thread[edit]
1 local thread = createThread(function(thread)
2 for i = 1, 5 do
3 print("Worker step " .. tostring(i))
4 sleep(500)
5 end
6 end)
Use synchronize for main-thread work[edit]
1 local thread = createThread(function(thread)
2 local result = "Finished background work"
3
4 synchronize(function()
5 print(result)
6 end)
7 end)
Create a thread from a named function[edit]
1 local function worker(thread, message)
2 print(message)
3 end
4
5 local message = "Running named worker"
6
7 local thread = createThread(worker, message)
Pass multiple values[edit]
1 local thread = createThread(function(thread, a, b, c)
2 print("A: " .. tostring(a))
3 print("B: " .. tostring(b))
4 print("C: " .. tostring(c))
5 end, 10, "text", true)
Store the returned Thread object[edit]
1 local workerThread = createThread(function(thread)
2 print("Thread is running")
3 end)
4
5 print("Returned thread: " .. tostring(workerThread))
Guard thread creation behind a condition[edit]
1 local shouldStart = true
2
3 if shouldStart then
4 createThread(function(thread)
5 print("Conditional thread started")
6 end)
7 end