This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
DannySMc's profile picture

[ANSWERED]: Splitting a string and getting the two numbers inside the string as separate variables

Started by DannySMc, 03 February 2015 - 08:51 AM
DannySMc #1
Posted 03 February 2015 - 09:51 AM
So I have a string:

str = "sector12x91"

I need to ge the 12 and the 91 into two separate variables as a number.

Changing to a number is simple, the problem I have is that number may not always be two digits, like it could have: sector1x1 or sector134x225.

So I need to split the string from sector to get the last set of numbers, but then somehow iterate over it grabbing the first numbers then using the 'x' add the next few numbers into another variable.

So I need to get "sector12x21" to:

worldxid = 12
worldyid = 21

Any help? I have the following code from others but this is annoying me because I can get the numbers, but only as one number, or in a table… :(/>

Anyway sorry here is the code I have:

(It's a mess but the code after the multi-line comment to the last two lines is what I have):


--[[local worldname = "space12x7"
local worldsector = string.sub(worldname, 6)
local worldxid = string.sub(worldsector, 1, 1)
local worldyid = string.sub(worldsector, 3)
print("X: "..worldxid..", Y: "..worldyid)]]

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 = "space1x1"

res={}
local data = str:gsub('%d%d%d',function(n)res[#res+1]=tonumber(n)end)

Thanks guys! :

(EDIT: it is indented on my code, it just never indents on this forum :(/>)

EDIT: Answered, the code was:


str = "something123x456"
local s1, s2 = str:match("(%d+)x(%d+)")
local n1, n2 = tonumber(s1), tonumber(s2)
Edited on 03 February 2015 - 11:20 AM
InDieTasten #2
Posted 03 February 2015 - 02:21 PM
You may want your pattern to be "(%d+)x(%d+)$", which expresses the pattern to be anchored right at the end. Just to be save, as I don't know, whether your "sector" or "something" can include numbers and x's ;)/>
DannySMc #3
Posted 04 February 2015 - 09:08 AM
You may want your pattern to be "(%d+)x(%d+)$", which expresses the pattern to be anchored right at the end. Just to be save, as I don't know, whether your "sector" or "something" can include numbers and x's ;)/>

It can have any of the two numbers like so:
sector1x1
sector12x34
sector2334x35

The code I tested works, but thanks anyway :D/>