试图将其转换为字符串customLog2 = {}
哪个看起来像Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
我试过这个
local Data = string.format( "LogBook = %s ", customLog2 )
但是因为 CustomLog 是一个数组而不是字符串或数字,所以我无法插入它。我试图将数组变成一个字符串
VariableFile:write(Data)
因此,如果有人可以提供帮助,那就太棒了,谢谢。所以我希望我的输出看起来像这样
"local Data = string.format( "LogBook = %s ", customLog2 )"
所以我可以使用 :write 然后在我新创建的文件中它应该看起来像这样 Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
所以这个功能可以期待一件事。
function TableSerialization(t, i)
local text = "{\n"
local tab = ""
for n = 1, i + 1 do --controls the indent for the current text line
tab = tab .. "\t"
end
for k,v in pairs(t) do
if type(k) == "string" then
text = text .. tab .. "['" .. k .. "'] = "
else
text = text .. tab .. "[" .. k .. "] = "
end
if type(v) == "string" then
text = text .. "'" .. v .. "',\n"
elseif type(v) == "number" then
text = text .. v .. ",\n"
elseif type(v) == "table" then
text = text .. TableSerialization(v, i + 1)
elseif type(v) == "boolean" then
if v == true then
text = text .. "true,\n"
else
text = text .. "false,\n"
end
elseif type(v) == "function" then
text = text .. v .. ",\n"
elseif v == nil then
text = text .. "nil,\n"
end
end
tab = ""
for n = 1, i do --indent for closing bracket is one less then previous text line
tab = tab .. "\t"
end
if i == 0 then
text = text .. tab .. "}\n" --the last bracket should not be followed by an comma
else
text = text .. tab .. "},\n" --all brackets with indent higher than 0 are followed by a comma
end
return text
end
我的输入数组可以说看起来像这样 Log = { Group = WestAPC } 现在这不起作用,因为 WestAPC 不是字符串但如果 WestAPC 看起来像这个“WestAPC”,它就可以工作。我需要它不是字符串形式。
最佳答案
需要明确的是,customLog 是一个表——即键值对的关联数组。这是迭代所有键/值对并将这些对连接成一个字符串的简单方法:
s = ""
t = {"a", "b", "c", 123, 456, 789} -- sample table
t.someKey = "some value" -- just an extra key value, to show that keys can be strings too
for k, v in pairs(t) do
s = s .. k .. ":" .. v .. "\n" -- concatenate key/value pairs, with a newline in-between
end
print(s)
当然,如果一个键的值是另一个表 {},那么您将需要一些额外的逻辑来递归迭代这些嵌套表。我会把它留给你作为练习:)
编辑 1:
将表格打印为字符串,显示变量值
s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
s = s .. "{"
for k, v in next, Log do
s = s .. "{"
for vk, vv in next, v do
if next(v, vk) ~= nil then
s = s .. vk .. " = " .. vv .. ", "
else
s = s .. vk .. " = " .. vv
end
end
if next(Log, k) ~= nil then
s = s .. "}, "
else
s = s .. "}"
end
end
s = s .. "}"
print(s)
编辑2:
将表格打印为字符串,显示变量名称
s = ""
local ID = 123
local Numbers = 456
local Log = { {Group = ID, Pos = Numbers}, {Group = ID, Pos = Numbers} }
s = s .. "{"
for k, v in next, Log do
s = s .. "{"
i = 1
for vk, vv in next, v do
name = debug.getlocal(1, i)
if next(v, vk) ~= nil then
s = s .. vk .. " = " .. name .. ", "
else
s = s .. vk .. " = " .. name
end
i = i + 1
end
if next(Log, k) ~= nil then
s = s .. "}, "
else
s = s .. "}"
end
end
s = s .. "}"
print(s)
关于arrays - 在LUA中将数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50958778/