我想知道是否有办法检查一个函数之前是否至少被调用过一次,或者这是否是对该函数的第一次调用(通过任何方法),或者如果有办法检查Lua VM或应用程序是否刚刚启动。。。前者是优选的。然后检查应用程序/LuaVM是否正在关闭,并进行快速的最终调用。
这是我的功能
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 .. "nn" .. error .. "n"
error_log:write(errors)
error_log:close()
end
__Error("This is an error")
这是一个错误记录函数,将在多个脚本、函数、类等中使用,将所有错误记录到一个文件中。我想做的是让time_data只出现在这个函数的第一次调用中,因为在那之后就不需要它了,而且看起来很糟糕。那么,有没有一种方法可以用这个函数做到这一点呢?如果可能的话,我宁愿不更改发送给它的参数和date_time变量。
感谢
使用闭包:
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()
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
这就是我和我朋友想出的答案。这个有效吗?