简体   繁体   English

Lua:拆分字符串并将两个数字作为单独的变量

[英]Lua: Splitting a string and getting the two numbers as separate variables

I have searched a few places and to no avail I can't find anything. 我已经搜索了几个地方,但无济于事。 So here is what I need to do: I have a string: "something123x456", I need to get the 123 and 456 as separate numbers. 所以这是我需要做的:我有一个字符串:“ something123x456”,我需要将123和456作为单独的数字来获取。 I know that if the numbers was always 3 digits long then that is a lot easier, but they could all be different.. For example the 123 and 456 represent X and Y values in a game; 我知道,如果数字总是3位长,那会容易得多,但它们都可以不同。例如,123和456表示游戏中的X和Y值; so they could be something2x5 or something2x98 etc. 因此它们可能是something2x5或something2x98等。

I need to somehow remove the "something", and then get the first set of digits and save them to an variable called worldxid and then remove the "x" and then take the last few digits and add them to worldyid. 我需要以某种方式删除“东西”,然后获取第一组数字并将其保存到名为worldxid的变量中,然后删除“ x”,然后获取最后几位数字并将其添加到worldyid中。

NOTE: This is used in an emulator for a game so there are API calls: textutils. 注意:这在游戏的仿真器中使用,因此有API调用:textutils。 I have the following code: 我有以下代码:

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))

Thanks in advance! 提前致谢!

Something like this? 像这样吗

str = "something123x456"
local s1, s2 = str:match("(%d+)x(%d+)")
local n1, n2 = tonumber(s1), tonumber(s2)

Try this: 尝试这个:

s = "something123x456"
worldxid, worldyid = s:match("(%d+).-(%d+)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM