Page 1 of 1

String to Table?

Posted: Fri Mar 10, 2017 1:44 am
by LuaChristopher
So, I'm making this small little pixel art program that draws according to a table; and the table can be changed by either drawing yourself or dropping a file into the program to draw the file's code. But the small problem is, I can't figure out a way to convert the string into tables.

Example of the File that is Imported

Code: Select all

{ {x,y,colornumber},{x,y,colornumber},{x,y,colornumber},*So on, so on* }
Main.lua: filedropped

Code: Select all

function love.filedropped(file)
	ClearCanvas()
	Canvas = file:read()
end
But it returns:

Code: Select all

(table expected, got string)
Now, I've read other posts and searched online but I just can't seem to make a string into a table and make that into a table.

Re: String to Table?

Posted: Fri Mar 10, 2017 2:44 am
by Sir_Silver
Um, I don't fully understand what the problem is that you're having, but, if you want a way to turn a string into a table, I wrote this up in like 30 seconds :P

Code: Select all

function string.toTable(string)
	local table = {}
	
	for i = 1, #string do
		table[i] = string:sub(i, i)	
	end
	
	return table
end
Just call this function and pass in your string, and it will return a table for you to use!

Re: String to Table?

Posted: Fri Mar 10, 2017 3:13 am
by davisdude
Even easier (assuming the string is a serialized table, and you're not very concerned with security), you could do

Code: Select all

str = '{ x = 2, y = 2, z = 5 }'

function stringToTable( str )
    return loadstring( 'return ' .. str )()
end

tab = stringToTable( str )
print( tab.z ) -- 5

Re: String to Table?

Posted: Fri Mar 10, 2017 8:54 pm
by LuaChristopher
Oh Thanks! This worked for me!