What's the Lua to get the current working directory on Windows XP SP3 (or to get the directory of the currently-running Lua file)? I prefer not to use LuaFileSystem.
I can't use os.execute("cd")
because os.execute
always starts from my home directory (and thus always yields C:\Documents and Settings\username
).
Lua by default doesn't have a "native" way of supporting the concept of "current directory", or, in fact, the concept of "directory".
The proper way to get the current directory is using a library that provides folder support. There are several - I recommend luafilesystem.
Once it is installed, you can get the current directory by executing:
lfs.currentdir()
This will work on windows, linux and mac.
Beware though that these external libraries usually involve some binary packages. Depending on your setup, you might have to compile it before being able to use it.
EDIT:
Note that when a file is included via require
, then the expression {...}[1]
returns the path used by the require
directive. It is not exactly the path because:
.lua
at the end of the file.package.path
But if all you need is the "require-like path" of the file (maybe to require files next to it) then you can get it by doing this at the very beginning of the file:
local PATH = (...):match("(.+)%.[^%.]+$") or (...)
If a file called baz.lua
is required with require 'foo.bar.baz'
, then PATH
will be foo.bar
.