Reputation: 55
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
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
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