I receive the following error when I try to run my code:
lua:readFile.lua:7: attempt to call method 'split' (a nil value)
I am teaching myself Lua and doing some exercises. I am trying to parse out the individual values in a text file and then do stuff with them. I can open the file and if I don’t try to parse out the values I can print the contents.
I have tried, separately:
dollars, tickets = line:split(" ")
dollars, tickets = line:split("(%w+)", " ")
Along with several other iterations I cannot recall at this point.
Here is my code:
myfile = io.open("C:\\tickets.txt", "r")
if myfile then
print("True") --test print
for line in myfile:lines() do
local dollars, tickets = unpack(line:split(" "))
print(dollars)
end
end
print("Done") --test print
myfile:close()
Here is the content of the tickets.txt file in its entirety:
250 5750
100 28000
50 35750
25 18750
I am obviously missing something in the split method but I do not know enough to know what.
Regards.
The string library in Lua doesn’t include a ‘split’ function. You will have to implement one yourself (there’s examples on the Lua wiki), or use Lua’s pattern matching functionality to parse out the pieces. For example, you could do something like this: