gpt4 book ai didi

Lua,修改打印功能

转载 作者:行者123 更新时间:2023-12-04 03:03:47 28 4
gpt4 key购买 nike

我正在用 lua 打印函数编写一个通用的 Log() 函数:

Log (variable, 'String: %s ', str, 'Word: %d', w)

目前我正在使用以下方法:

print(string.format (variable, 'String: %s ', str, 'Word: %d', w))

我试过类似的方法:

Log = function(...) begin
return print(string.format(...))
end

但它不起作用,这是正确的做法吗?或者有没有更好更通用的方法来完成这项工作?

最佳答案

如果您只想打印一系列值,您可以使用 print 来实现:

print(variable, 'String: %s ', str, 'Word: %d', w)

您似乎想要的是更复杂的东西。您的算法似乎是:

  1. 对于每个参数:
    1. 如果参数不是字符串,则将其转换为字符串并打印。
    2. 如果参数是一个字符串,计算出它有多少个 % 模式(让我们称这个数字为 k)。传递 string.format 当前参数字符串和后面的 k 参数,打印结果字符串。提前 k 个参数。

这是一种比单线系统复杂得多的算法。

使用 Lua 5.3,下面是这样一个函数的样子(注意:几乎没有测试过的代码):

function Log(...)
local values = {}

local params = table.pack(...)

local curr_ix = 1
while (curr_ix <= params.n) do
local value = params[curr_ix]
if(type(value) == "string") then
--Count the number of `%` characters, *except* for
--sequential `%%`.
local num_formats = 0
for _ in value:gmatch("%%[^%%]") do
num_formats = num_formats + 1
end

value = string.format(table.unpack(params, curr_ix, num_formats + curr_ix))

curr_ix = curr_ix + num_formats
end

values[#values + 1] = value
curr_ix = curr_ix + 1
end

print(table.unpack(values))
end

关于Lua,修改打印功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46460303/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com