Heres the code, it's heavily commented so everyone can understand it, if not then don't hesitate to ask.
This code can only load files with the following format:
The last number should always have a comma (,) at the end and it can have as many numbers(each composed of only one digit, 1=OK 11=NO) and as many lines as you want.
They can be totaly random, ex:
Code: Select all
1,0,1,0,1,
0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,
1,2,2,0,2,2,
1,4,1,3,5,7,5,
What this code does is it reads the lines from a text file and divides each line into numbers (each number can have more then one digit: 1,12,123...etc) into a table variable (data[no. of line][no. of char]), this code can be mostly used to load maps from files with the above format.
Code: Select all
chars=1 --Variable controlling the characters flow in the data table
lines=1 --Variable controlling the lines flow in the data table
data={} --Table holding all the lines and characters formed by: data[no. of line][no. of char]
file = assert(io.open('temp.txt'))
for line in file:lines() do
data[lines]={} --Creats a new table for the line
string.gsub(line,'%d,', --'%d,' means everytime it finds a number followed by a ','
function(a) --That number and the comma are stored in variable a
string.gsub(a,'%d', --Everytime it finds a number (%d = digit)
function(b) --Stores the number in variable b
data[lines][chars]=b --Stores the number inside variable b in the table
chars=chars+1 --Adds one to the variable controlling the characters flow in the data table
end
)
end
)
chars=1 --Reverts the char count
lines=lines+1 --Adds one to the variable controlling the lines flow in the data table
end
--debugger
for a=1,#data do
for b=1,#data[a] do
print(data[a][b])
end
print(unpack(data[a]))
end
(You can remove the debugger code)
(
EDIT: the data table holds STRING value and NOT numeric value, so when you want call it in you code you do ex:
if data[1][1]=='1'
instead of
if data[1][1]==1
)
You can all use this code to do whatevs you want, put it in a function if you like, it's yours
Thanks for all the help people specialy to raidho36 for enlightning me on the string.gsub function
(if you don't want to convert my code to a function or you just don't like it then you should check out Omnivore's or MPQC's function)