• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

How to Create a Thread which prints a word ervery 3 seconds in lua? (1 Viewer)

reezy

Newcomer
Joined
Apr 23, 2022
Messages
2
Reaction score
0
I need help with creating a Thread which gives out a word every 3 Seconds. ("Hallo")
And this should happen endless how to do this in lua?
Thanks for your time :)
 

stetre

Member
Rank: II
Joined
Jan 8, 2020
Messages
103
Reaction score
58
Location
Italy
Website
github.com
By 'thread' do you mean a coroutine, or are you just happy with a single threaded script that does this and nothing else?
 

stetre

Member
Rank: II
Joined
Jan 8, 2020
Messages
103
Reaction score
58
Location
Italy
Website
github.com
the second would make me happy :)

That's fairly simple, with a few caveats (see below):

Lua:
local next_time = os.time() + 3

while true do
    if os.time() > next_time then
        print(string.format("[%d] Hallo", os.time())) -- print also the current time
        next_time = next_time + 3
    end
end

The above code assumes that os.time() returns the time in seconds (which is not guaranteed on all systems, as stated in the manual), and even if it does, the resolution is 1 second. As a consequence, the interval between successive prints will be 3 seconds +/- 1 second.

If you need more precise timing, you must resort to an external library that provides you with a function that gives you a monothonic time with a better resolution.

One alternative is to use socket.gettime() from LuaSocket, and use it to replace os.time in the above code.

Another alternative is to use the MoonTimers module (wrote by myself), that provides you with asynchronous timers. With timers, your example could be something like this:

Lua:
local timers = require("moontimers")

local function callback(tmr, exptime)
    print(string.format("[%.3f] Hallo!", timers.now()))
    tmr:start(exptime + 3)
end

-- Create a timer passing it the callback to execute at its expiration:
local T = timers.new(0, callback)
-- Start the timer:
T:start(timers.now() + 3)

-- Enter the event loop:
while true do
    timers.trigger()
end

EDIT: fixed link to os.time() in Lua manual.
 
Top