简体   繁体   中英

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. 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; so they could be something2x5 or something2x98 etc.

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.

NOTE: This is used in an emulator for a game so there are API calls: 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+)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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