mhiekuru
mhiekuru

Reputation: 55

What is the right pattern to for numbers with negative symbol?

I have a string of numbers separated by spaces and I need to store them in a table but for some reason negative symbol is not getting recognize.

cord = "-53 2 -21"
map = {}
for num in cord:gmatch("%w+") do 
    table.insert(map, num) 
end
map[1], map[2], map[3] = tonumber(map[1]), tonumber(map[2]), tonumber(map[3])
print(map[1])
print(map[2])
print(map[3])

This is the output I'm getting:

53
2
21

I think the problem is with the pattern I'm using, what should I change?

Upvotes: 2

Views: 1747

Answers (2)

Yu Hao
Yu Hao

Reputation: 122383

The pattern "%w" is for alphanumeric characters, which doesn't include -, use this pattern instead:

"%-?%w+"

or better:

"%-?%d+"

since numbers are all you need.

Upvotes: 2

lhf
lhf

Reputation: 72312

%w+ does not attempt to mach only numbers, so try %S+ to get all "words", that is, all sequences of non-zero characters.

If you want to match only numbers, try %-?%d+. Note the optional minus sign in the pattern. Note also that you must escape the minus sign.

Upvotes: 2

Related Questions