Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LUA: String to variables

Tags:

split

lua

weather

I have a string containing weather data. I want to assign each of the values in the string a variable

string = "12-05-17 12:48:48 12.3 23 -8.2 1 2 225 0.0 0.0 992.3 SW 1 m/s C 
hPa mm 49.8 +0.1 0.6 60.0 0.0 21.5 31 12.3 +0.7 13.0 11:31 1.2 01:31 4 10:40 
7 09:36 992.4 12:28 989.4 00:00 1.9.4 1099 6 12.3 12.3 0 0.00 0 176 0.0 24 1 
0 S 2560 m 8.7 0.0 750 0 "


s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,
s22,s23,s24,s25,s26,s27,s28,s29,s30,s31,s32,s33,s34,s35,s36,s37,s38,s39,s40, 
s41,s42,s43,s44,s45,s46,s47,s48,s49,s50,s51,s52,s53,s54,s55,s56,s57,s58 = 
response:match("
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s([^%s]+)%s
([^%s]+)%s([^%s]+)")

Date = s1
Time = s2
Temp = s3
Humidity = sS4
WindSpeed = s13
HighTemp = s27
CloudBase = s53

However this does not work. I am getting the error message below;

"too many captures stack traceback: in function 'string.match' main.lua:2: in main chunk

Please help!

like image 687
J Dunberg Avatar asked Dec 24 '22 18:12

J Dunberg


2 Answers

I think you'll be better off using an array:

data = "12-05-17 12:48:48 12.3 23 -8.2 1 2 225 0.0 0.0 992.3 SW 1 m/s C hPa mm 49.8 +0.1 0.6 60.0 0.0 21.5 31 12.3 +0.7 13.0 11:31 1.2 01:31 4 10:40 7 09:36 992.4 12:28 989.4 00:00 1.9.4 1099 6 12.3 12.3 0 0.00 0 176 0.0 24 1 0 S 2560 m 8.7 0.0 750 0 "

value = { }
n = 0

for v in data:gmatch("%S+") do
    n = n + 1
    value[n]=v
end

Date = value[1]
Time = value[2]
Temp = value[3]
Humidity = value[4]
WindSpeed = value[13]
HighTemp = value[27]
CloudBase = value[53]

print(Date,Time,Temp,Humidity,WindSpeed,HighTemp,CloudBase)
like image 85
lhf Avatar answered Jan 11 '23 21:01

lhf


To split string, use gmatch:

local my_string = [[12-05-17 12:48:48 12.3 23 -8.2 1 2 225 0.0 0.0 992.3 SW 1 m/s C hPa mm 49.8 +0.1 0.6 60.0 0.0 21.5 31 12.3 +0.7 13.0 11:31 1.2 01:31 4 10:40 7 09:36 992.4 12:28 989.4 00:00 1.9.4 1099 6 12.3 12.3 0 0.00 0 176 0.0 24 1 0 S 2560 m 8.7 0.0 750 0  ]]

local vars= {}
for word in my_string:gmatch('(.-)[%s]+') do
     vars[#vars+1] = word
      print(#vars,word)
end
local Date = vars[1]
local Time = vars[2]
local Temp = vars[3]
-- and etc.

(long strings can be enclosed in square brackets [[]])

like image 29
Mike V. Avatar answered Jan 11 '23 22:01

Mike V.