String to Table?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
LuaChristopher
Prole
Posts: 2
Joined: Fri Mar 10, 2017 1:10 am

String to Table?

Post 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.
User avatar
Sir_Silver
Party member
Posts: 286
Joined: Mon Aug 22, 2016 2:25 pm
Contact:

Re: String to Table?

Post 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!
davisdude
Party member
Posts: 1154
Joined: Sun Apr 28, 2013 3:29 am
Location: North Carolina

Re: String to Table?

Post 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
GitHub | MLib - Math and shape intersections library | Walt - Animation library | Brady - Camera library with parallax scrolling | Vim-love-docs - Help files and syntax coloring for Vim
LuaChristopher
Prole
Posts: 2
Joined: Fri Mar 10, 2017 1:10 am

Re: String to Table?

Post by LuaChristopher »

Oh Thanks! This worked for me!
Post Reply

Who is online

Users browsing this forum: No registered users and 9 guests