【问题标题】:Lua: First Call to Function OR VM Launch/Startup CheckLua:第一次调用函数或 VM 启动/启动检查
【发布时间】:2014-11-09 23:33:45
【问题描述】:

我想知道是否有一种方法可以检查一个函数是否至少被调用过一次,或者这是第一次调用该函数(通过任何方法),或者是否有一种方法可以检查Lua VM 或应用程序刚刚启动/启动......前者是首选。然后检查应用程序/Lua VM 是否正在关闭并进行快速最终调用。

这是我的功能

function __Error(error)
    local error_log = io.open("Logs/Error.log", "a+")
    local log_time_date = os.date("Error Log: %A, %B %d %Y %I" .. ":" .. "%M" .. ":" .. "%S %p")
    local errors = "-----\n" .. log_time_date .. "\n\n" .. error .. "\n"
    error_log:write(errors)
    error_log:close()
end
__Error("This is an error")

这是一个错误记录功能,可用于多个脚本、函数、类等,将所有错误记录到一个文件中。我想做的事情是让 time_data 只出现在这个函数的第一次调用中,因为之后就不需要它并且看起来很糟糕。那么有没有办法用这个功能做到这一点?如果可能,我宁愿不更改发送给它的参数和 date_time 变量。

谢谢

【问题讨论】:

    标签: function logging lua call init


    【解决方案1】:

    使用闭包:

    do
        local first = true -- __Error can access/modify this, and it will persist across calls
        local error_log -- Same here
    
        function __Error(error)
            if first then
                -- Repeatedly opening/closing the log file is bad for performance, just open it once and keep it open.
                -- Also, don't need + in the file mode if you're not reading.
                error_log = io.open("Logs/Error.log", "a")
                local log_time_date = os.date("Error Log: %A, %B %d %Y %I" .. ":" .. "%M" .. ":" .. "%S %p")
                local header = "-----\n" .. log_time_date .. "\n"
                error_log:write(header)
                first = false
            end
    
            error_log:write(error, "\n")
        end
    
        function __Close_error_log()
            if error_log then error_log.close() end
        end
    end
    
    __Error("This is an error")
    
    -- at end of program
    __Close_error_log()
    

    【讨论】:

    • 看起来不错,我会测试一下。如果我想保留以前的日志,我不需要 + 吗?
    • 我测试了它,但它仍然想出了第二次通话的时间日期。它对你有用吗?
    • 确保您没有多次创建该函数。另外,如果您是aappending,则不需要+ 来保留内容。
    • 根据我所见,该函数仅创建一次。而闭包允许在外部脚本中调用函数,只要它在全局表中?
    • 这是我在你的脚本上得到的输出...----- Error Log: Sunday, November 09 2014 07:37:37 PM This is an error ----- Error Log: Sunday, November 09 2014 07:38:10 PM This is an error Hi Hi 我用 Hi\n 调用了该函数两次,但任何其他时候我调用该函数,时间都会打印出来。
    【解决方案2】:
    logged_time_date = logged_time_date
    
    function __Error(error)
        local error_log = io.open("Logs/Error.log", "a+") -- a+ is needed in case the file gets deleted
        if logged_time_date == nil then
            local log_time_date = os.date("Error Log: %A, %B %d %Y %I" .. ":" .. "%M" .. ":" .. "%S %p")
            local time_stamp = "----\n" .. log_time_date .. "\n----\n"
            error_log:write(time_stamp)
            logged_time_date = true
        end
        error_log:write(error, "\n")
    end
    

    这是我和我的朋友想出的答案。这有效吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2018-01-23
      • 1970-01-01
      相关资源
      最近更新 更多