我对这个Lua代码做错了什么

时间:2014-12-29 14:51:02

标签: lua sleep

这是我的代码

function masspoke(serverConnectionHandlerID, clientID, txt)
    local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
    sleep(1)
    local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
    if error == ts3errors.ERROR_not_connected then
        ts3.printMessage(serverConnectionHandlerID, "Error: Not Connected")
        return
    elseif error ~= ts3errors.ERROR_ok then
        print("Getting Error: " .. error .. "by poking the ID: " .. clientID)
        return
    end
    ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
end

我的错误是

  

试图打电话给全球“睡眠”。 (零值)

2 个答案:

答案 0 :(得分:1)

Lua中没有sleep函数,因此您会收到错误。如果您可以访问luasocket,那么实现所需内容的最简单方法是使用socket.sleepthisthis SO问题中列出了其他几个选项。

答案 1 :(得分:0)

Lua不提供睡眠功能。有几种方法可以实现一个as discussed on the Lua wiki,一定要看看。基于套接字的解决方案是比定时器循环更好的选择,因为它不会旋转CPU(保持忙碌),但它需要您安装第三方sockets库。在所有解决方案中,您的应用无法执行任何其他操作,而是等待时间过去。

你应该问你是否真的需要在一段时间内阻止你的线程,也就是说为什么不循环直到满足某个条件。在您的情况下,这可以是循环,直到从请求获得OK状态,或者已经过了一定量的时间。这样,循环将在你的'#34;继续'#34;达到条件,但如果达到条件需要太长时间,函数将返回。这样做的另一个好处是,您可以在每次循环时为TS应用程序提供处理其他事件的机会。

看起来像这样(未经测试):

function masspoke(serverConnectionHandlerID, clientID, txt)
    local start = os.clock()  -- start timing
    local MAX_WAIT_SECS = 1   -- seconds to wait for OK
    local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
    while error ~= ts3errors.ERROR_ok do
        if os.clock() - start > MAX_WAIT_SECS then  -- too long, give up!
            if error == ts3errors.ERROR_not_connected then
                ts3.printMessage(serverConnectionHandlerID, "Error: Not Connected")
            else
                print("Getting Error: " .. error .. "by poking the ID: " .. clientID)
            end
            return
        end
        error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
    end
    -- now that ts poke is ok, do whatever: 
    ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt)
end

我认为以上是一种更清洁的方法,意图更清晰。如果你真的想通过套接字模块睡眠主线程,那么把它放在你的masspoke()函数之前:

require "socket"  -- you need to install socket lib manually
function sleep(sec)
    socket.select(nil, nil, sec)
end

但是http://lua-users.org/wiki/SleepFunction上还有其他几个值得尝试的选项(取决于你的平台,以及你是否希望你的程序在多个平台上运行),而不需要安装第三个 - 党的图书馆。请务必仔细阅读该页面并尝试其显示的内容。