Lua: 拆分字符串并将两个数字作为单独的变量
Lua: Splitting a string and getting the two numbers as separate variables
我找了几个地方都没有找到任何东西。所以这是我需要做的:
我有一个字符串:"something123x456",
我需要将 123 和 456 作为单独的号码获取。
我知道,如果数字总是 3 位长,那就容易多了,但它们可能都不同。例如,123 和 456 代表游戏中的 X 和 Y 值;所以它们可能是 something2x5 或 something2x98 等等
我需要以某种方式删除 "something",然后获取第一组数字并将它们保存到一个名为 worldxid 的变量中,然后删除 "x" 然后取最后几位数字和将它们添加到 worldyid。
注意:这是在游戏模拟器中使用的,因此有 API 个调用:textutils。
我有以下代码:
local tNumbers = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
}
str = "space1x1"
something = {}
new = {}
for i = 1, #str do
local c = str:sub(i,i)
-- do something with c
print(c)
table.insert(something, c)
end
for k, v in ipairs(something) do
for _,v1 in ipairs(tNumbers) do
if v == v1 then
table.insert(new, v)
elseif v == "x" then
break
end
end
end
table.concat(new)
print(#new)
print(textutils.serialize(new))
提前致谢!
试试这个:
s = "something123x456"
worldxid, worldyid = s:match("(%d+).-(%d+)")
是这样的吗?
str = "something123x456"
local s1, s2 = str:match("(%d+)x(%d+)")
local n1, n2 = tonumber(s1), tonumber(s2)
我找了几个地方都没有找到任何东西。所以这是我需要做的: 我有一个字符串:"something123x456", 我需要将 123 和 456 作为单独的号码获取。 我知道,如果数字总是 3 位长,那就容易多了,但它们可能都不同。例如,123 和 456 代表游戏中的 X 和 Y 值;所以它们可能是 something2x5 或 something2x98 等等
我需要以某种方式删除 "something",然后获取第一组数字并将它们保存到一个名为 worldxid 的变量中,然后删除 "x" 然后取最后几位数字和将它们添加到 worldyid。
注意:这是在游戏模拟器中使用的,因此有 API 个调用:textutils。 我有以下代码:
local tNumbers = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
}
str = "space1x1"
something = {}
new = {}
for i = 1, #str do
local c = str:sub(i,i)
-- do something with c
print(c)
table.insert(something, c)
end
for k, v in ipairs(something) do
for _,v1 in ipairs(tNumbers) do
if v == v1 then
table.insert(new, v)
elseif v == "x" then
break
end
end
end
table.concat(new)
print(#new)
print(textutils.serialize(new))
提前致谢!
试试这个:
s = "something123x456"
worldxid, worldyid = s:match("(%d+).-(%d+)")
是这样的吗?
str = "something123x456"
local s1, s2 = str:match("(%d+)x(%d+)")
local n1, n2 = tonumber(s1), tonumber(s2)