Save String to File (code snippet)

Description

This saves the contents of a string variable into a text file.

See counterpart Load String From File (code snippet).

Requires: None

Code

SaveStringToFile.fh_lua
-- Open File and return Handle --
function OpenFile(strFileName,strMode)
	local fileHandle, strError = io.open(strFileName,strMode)
	if not fileHandle then
		error("\n Unable to open file in \""..strMode.."\" mode. \n "..strFileName.." \n "..tostring(strError).." \n")
	end
	return fileHandle
end -- function OpenFile
 
-- Save string to file --
function SaveStringToFile(strString,strFileName)
	local fileHandle = OpenFile(strFileName,"w")
	fileHandle:write(strString)
	assert(fileHandle:close())
end -- function SaveStringToFile

Usage

local tblFile = {}
table.insert(tblFile,"1st text line")
table.insert(tblFile,"2nd text line")
table.insert(tblFile,"3rd text line")
SaveStringToFile(table.concat(tblFile,"\n").."\n","D:\\temp\\example.txt")