[英]Lua: Splitting a string and getting the two numbers as separate variables
我已經搜索了幾個地方,但無濟於事。 所以這是我需要做的:我有一個字符串:“ something123x456”,我需要將123和456作為單獨的數字來獲取。 我知道,如果數字總是3位長,那會容易得多,但它們都可以不同。例如,123和456表示游戲中的X和Y值; 因此它們可能是something2x5或something2x98等。
我需要以某種方式刪除“東西”,然后獲取第一組數字並將其保存到名為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))
提前致謝!
像這樣嗎
str = "something123x456"
local s1, s2 = str:match("(%d+)x(%d+)")
local n1, n2 = tonumber(s1), tonumber(s2)
嘗試這個:
s = "something123x456"
worldxid, worldyid = s:match("(%d+).-(%d+)")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.