Reputation: 1205
I am trying to get the last 4 characters of a field in a lua table.
My csv file looks like this: 1234, http://myurl.com
local list = {}
for line in io.lines("x.csv") do
local mediaId, fURL = line:match("([^,]+),([^,]+)")
list[#list + 1] = { mediaId = mediaId, fURL = fURL }
end
print(list[1].mediaId) -- 1234
print(list[1].fURL) -- http://myurl.com
print(list[1].fURL.tostring().sub(list[1].fURL.tostring().len() - 4)) -- expected result: last 4 character of string, eg. .com
What I need now are the 4 last characters. It does not matter what they are, no need for any checks just the 4 last characters. My code above causes a "attempt to call field 'tostring' (a nil value)" error. What do I need to do to correct it?
Upvotes: 1
Views: 726
Reputation: 1205
local bla = string.len(tostring(list[1].fURL)) - 3
print(string.sub(tostring(list[1].fURL), bla)) -- last 4 character, yes minus 3 = last 4 character.
Upvotes: 2
Reputation: 80639
You can store them as a new key in the table (The function used is string.sub
):
for line in io.lines("x.csv") do
local mediaId, fURL = line:match("([^,]+),([^,]+)")
list[#list + 1] = { mediaId = mediaId, fURL = fURL, last = fURL:sub(-4) }
end
and reference them outside of the loop as:
print( list[1].last )
Upvotes: 3