Creating a timer using Lua

前端 未结 6 870
粉色の甜心
粉色の甜心 2020-12-31 13:50

I would like to create a timer using Lua, in a way that I could specify a callback function to be triggered after X seconds have passed.

What would be the best way t

6条回答
  •  猫巷女王i
    2020-12-31 14:18

    On my Debian I've install lua-lgi packet to get access to the GObject based libraries.

    The following code show you an usage demonstrating that you can use few asynchronuous callbacks:

    local lgi = require 'lgi'
    local GLib = lgi.GLib
    
    -- Get the main loop object that handles all the events
    local main_loop = GLib.MainLoop()
    
    cnt = 0
    function tictac()
         cnt = cnt + 1
         print("tic")
         -- This callback will be called until the condition is true
         return cnt < 10
    end
    
    -- Call tictac function every 2 senconds
    GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, tictac)
    
    -- You can also use an anonymous function like that
    GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1,
                             function()
                                print( "There have been ", cnt, "tic")
                                -- This callback will never stop
                                return true
                             end)
    
    -- Once everything is setup, you can start the main loop
    main_loop:run()
    
    -- Next instructions will be still interpreted
    print("Main loop is running")
    

    You can find more documentation about LGI here

提交回复
热议问题