Strict string structure

Is there a way to strict a string structure to check if it like this? (1,2,3) I am asking for this because I mainly convert a normal string which should be structed like this “1,2,3” to a table {1,2,3} but I’m afraid that since it is an input box, many players would not input it correctly? I tried doing checks with str:find(",") but it’s not optimal. (Not to mention that it is a number only string so doing tonumber would void all commas).

function csvToTable(list) 	
	local out = {}
	for entry in string.gmatch(list, "[^,]+") do 
		table.insert(out, entry)
	end
	return out
end
print(csvToTable("1,2,3"))

Turns out the function already handles commas by itself, however is there a better way to remove/check for non numbers?

function csvToTable(list) 	
	local out = {}
	for entry in string.gmatch(list, "[^,]+") do 
		if tonumber(entry) == nil then
			continue
		end
		table.insert(out, entry)
	end
	if #out <= 1 then
		return false
	end
	return out
end

You just need to use the correct pattern:

function csvToTable(list)
    local out = {}

    for entry in list:gmatch("[-]?%d*%.?%d+") do
        table.insert(out, entry)
    end

    return out
end

local result = csvToTable("-10, +5, .4, 1,2,3, 4., 4.5, 9.008,  ,   828")

print(result)

As you can see, I’ve included negative numbers, positive numbers with and without + at the start, random spacing between the commas and decimals too, not just n.n decimals but also .n and n. (which some may use instead of normal decimals), there’s also an extra comma, I know, I just added it to show that it’s just ignored by the code. The pattern may look weird but it just matches for an optional negative sign, then zero or more numbers, then an optional decimal point and lastly, one or more digits after the decimal point, if it was found.

This works but is there a way to only include whole numbers? Like only positive rounded numbers (“1,2,3,4”)
I tried doing this pattern but it only includes single digit numbers.

function csvToTable(list)
    local out = {}

    for entry in list:gmatch("%d") do
		print(entry)
        table.insert(out, entry)
    end

    return out
end

local result = csvToTable("10,12,3,6")

print(result)
1 Like

Yea of course, something like this:

function csvToTable(list)
    local out = {}

    for entry in list:gmatch("(%d+)[,]?") do
        table.insert(out, entry)
    end

    return out
end

local result = csvToTable("10,12,3,6")
print(result)

This checks for one or more numbers and an optional comma after (since last numbers don’t have commas after them).

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.