Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use io.open in home directory - Lua

Tags:

io

macos

lua

I'm writing a Mac OS program, and I have the following lines:

os.execute("cd ~/testdir")
configfile = io.open("configfile.cfg", "w")
configfile:write("hello")
configfile:close()

The problem is, it only creates the configfile in the scripts current directory instead of the folder I have just cd' into. I realised this is because I'm using a console command to change directory, then direct Lua code to write the file. To combat this I changed the code to this:

configfile = io.open("~/testdir/configfile.cfg", "w")

However I get the following result:

lua: ifontinst.lua:22: attempt to index global 'configfile' (a nil value)
stack traceback:
ifontinst.lua:22: in main chunk

My question is, what's the correct way to use IO.Open to create a file in a folder I have just created in the users home directory?

I appreciate I'm making a rookie mistake here, so I apologise if you waste your time on me.

like image 578
Lewis Smith Avatar asked Nov 03 '15 09:11

Lewis Smith


1 Answers

You have problems with ~ symbol. In your os.execute("cd ~/testdir") is the shell who interprets the symbol and replaces it by your home path. However, in io.open("~/testdir/configfile.cfg", "w") is Lua who receives the string and Lua doesn't interprets this symbol, so your program tries to open a file in the incorrect folder. One simple solution is to call os.getenv("HOME") and concatenate the path string with your file path:

configfile = io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w")

In order to improve error messages I suggests you to wrap io.open() using assert() function:

configfile = assert( io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w") )
like image 114
Francisco Zamora-Martínez Avatar answered Nov 10 '22 14:11

Francisco Zamora-Martínez