Lua:调用函数的第一次或VM启动/启动检查

我想知道是否有一种方法可以检查一个函数是否已经被调用了至少一次,或者这是对函数的第一次调用(通过任何方法),或者是否有一种方法可以检查 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 变量。

谢谢

点赞
用户646619
用户646619

使用闭包:

do
    local first = true -- __Error 可以访问/修改它,并且它会持久化跨越调用
    local error_log -- 同上

    function __Error(error)
        if first then
           -- 多次打开/关闭日志文件对性能不利,只需打开一次并保持打开状态。
           -- 另外,如果不是读取文件,则文件模式中不需要加上 +。
            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("这是一个错误")

-- 程序结束时
__Close_error_log()
2014-11-09 23:43:57
用户3994105
用户3994105
logged_time_date = logged_time_date

function __Error(error)
    local error_log = io.open("Logs/Error.log", "a+") -- 需要用 a+,以防文件被删除。
    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

这是我和朋友想出来的答案。这个是否有效?

2014-11-10 04:54:25