4

I am beginning to learn Lua on my own with basically no prior programming knowledge. I understand the basics of types, functions, tables, etc. But in following the Lua tuts at Lua.org, I'm currently on the "Modules Tutorial" and am having issues understanding the proper/easiest way to call a file made into interactive mode.

If I used Notepad++ or Scite to create a file, can someone please help me understand how to open said file using the proper nomenclature to open it?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Pwrcdr87
  • 935
  • 3
  • 16
  • 36

1 Answers1

8

Assume that your file is named foo.lua, then in the Lua interpreter (i.e, the interactive mode), use loadfile. Note that loadfile does not raise error, so it's better to use assert with it.

f = assert(loadfile("foo.lua"))

It will load the chunk in foo.lua into the function f. Note that this will only load the chunk, not run it. To run it, call the function:

f()

If you need to run it immediately, you can use dofile:

dofile("foo.lua") 

Lua uses package.path as the search path which gets its default value from LUA_PATH. However, it's better to use proper relative path in practice.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 4
    A common idiom to do this in one step is `assert(loadfile("foo.lua"))()`; this loads and runs the file, and if loading didn't work, displays the error. – ToxicFrog Sep 17 '13 at 17:00
  • Thanks! I performed both `loadfile` and `assert` methods within the interactive mode and was successful! That clears that up. At first I got an error but quickly realized that my root folder for all of my Lua files was not within the Lua 5.1 root folder. A simple relocation of that file and everything ran perfectly! – Pwrcdr87 Sep 17 '13 at 17:50
  • Actually, I have another stupid question. What if I need to open a file in another directory (outside of the Lua 5.1 root folder)? If I was to run `assert(loadfile("foo.lua))()` and it was in a separate folder, how would the syntax change? Again thank you for your help! – Pwrcdr87 Sep 17 '13 at 18:26
  • @ToxicFrog Right, it's better to use `assert` since `loadfile` doesn't raise error, and I'll update the answer. But again, `loadfile` will only load the file, not run it. – Yu Hao Sep 18 '13 at 00:49
  • @Pwrcdr87 Use a proper relative path will do, or see the updated answer. – Yu Hao Sep 18 '13 at 00:50
  • You guys are great! Thank you so much for your help. I understand fully now. – Pwrcdr87 Sep 18 '13 at 11:33