Robin wrote:
The alternative is writing code that parses your text file. It's not very difficult, but the simpler and easier solution is the first one I mentioned.
I agree of course that getting it to work is easier, but making it work right (i.e. protecting the player from faulty code, for example) is much, much harder.
bbdude, this code should do what you want:
Code: Select all
function loadTableFromFile( filename )
tbl = {}
width = 0
height = 0
for line in io.lines(filename) do
-- make sure line ends with comma:
if line:sub(#line, #line) ~= "," then
line = line .. ","
end
-- remove all whitespace:
line = string.gsub(line, " ", "")
line = string.gsub(line, "\t", "")
height = height+1
tbl[height] = {} -- create a table for each line
for field in string.gmatch(line, "[^,]*,") do
-- remove comma from end:
field = field:sub(1, #field-1)
-- add at the end of tbl[i]:
tbl[height][#tbl[height]+1] = field
if #tbl[height] > width then
width = #tbl[height]
end
end
end
return tbl, height, width
end
And here's an example usage:
Code: Select all
function love.load()
t,h,w = loadTableFromFile( "table.txt" )
print("h,w: ", h, w)
-- print value at (2,3)
print(t[3][2])
-- print whole line:
for k,v in ipairs(t) do
line = ""
for j,v2 in ipairs(v) do
line = line .. v2 .. "\t"
end
print(line)
end
end
Note: the function will remove any whitespace from your file. I think this can be useful for formatting the level in a more readable way in case you need more than numbers as fields, and some field entries are longer than the other -> in this case, just add spaces to the shorter field names.
Also, values should be seperated by commas. It works with the example file you posted.
BUT you need to be careful: after using this function, your table will be indexed like this:
t[y][x]
to get the value at coordinates (x,y). This is a little counter-intuitive, but if you just switch the x and y values, you should be fine.
It can be changed, of course, to work like:
t[x][y]
If you need it this way, try it yourself and if you get stuck just ask us.
One thing this code does NOT make sure is that the lines are all the same length, i.e. the first line could have 4 elements and the second one three. If you need this to be true, you can add a check to the end of the function: just check if the length of each line #tbl[y] is the same as width, otherwise give out an error.
Hope this helps, happy coding!