Reputation: 2386
I try to write multiple lines to a file in Lua but I don't get how to do it. I tried this:
local category = io.open("/usr/home/game/share/locale/germany/category.txt", "w")
category:write(mysql_query("USE account; SELECT DISTINCT itemshop_categories.category AS a, itemshop_categories.id AS b FROM itemshop INNER JOIN itemshop_categories ON itemshop.category_id = itemshop_categories.id ORDER BY itemshop.category_id ASC;"))
category:close()
mysql_query gives me a table like this
{
{"1_1", "1_2"},
{"2_1", "2_2"},
{"3_1", "3_2"}
}
so I want to write this to the .txt file but it doesn't work. And if I get it to work, will I be able to read this file like this:
local category = io.open("/usr/home/game/share/locale/germany/category.txt", "r")
category:read()[2][1]
category:close()
to get "2_1" ?
Upvotes: 1
Views: 665
Reputation: 80921
You cannot directly write a table to a file. You have to serialize it. If you serialize it correctly you can then just load the file back as lua code to get an identical table as a result.
Writing a simple table serializer is not complicated. Writing a robust one is a fair bit harder. Luckily the fine folks on the lua-users.org wiki have written a number of such serialization mechanisms (of varying quality and feature support).
Find one that suits your purposes. http://lua-users.org/wiki/TableSerialization
Upvotes: 2
Reputation: 72312
You need to traverse the table returned by mysql_query
and write its contents by hand:
for k,v in ipairs(mysql_query("USE account; SELECT DISTINCT itemshop_categories.category AS a, itemshop_categories.id AS b FROM itemshop INNER JOIN itemshop_categories ON itemshop.category_id = itemshop_categories.id ORDER BY itemshop.category_id ASC;")) do
category:write(k,"\t",v,"\n")
end
To read it back, you read the file line by line (possibly using io.lines
), split each line into two fields, and process the fields as desired.
Upvotes: 2