stringluapattern-matchingopenwrt

Using gmatch captures to index a table


I want to get the index and x values. From gmatch function, i is the character so i failed this code. I want to get the values and indexes. Is there any solution from this?

val[1] = 24
fx = {}

for i, x in response_body[1]:gmatch([["(%w+)lId"%s*:%s*(%d+)]]) do
fc[i] = x
print(x)
end
/* x prints 14
            18
            23 */

if (val[1] ~= fc[1] and val[1] ~= fc[2] and val[1] ~= fc[3] ) then
val[1] = fc[1]

else
val[1] = val[1]
end

Solution

  • string.gmatch returns strings. So i and x are both strings in your code, given that you have a match of course.

    f[1] is not the same as f["1"].

    So in your code fc[1] and so on are nil values and hence cannot equal 24

    You can use tonumber to convert a string to a number value. But keep in mind that converting an alphanumeric character as matched by %w is not necessarily convertible to a number. You have to avoid using nil as a table index or you will get an error.