I need to execute a Lua script from inside another Lua script. How many ways are there, and how do I use them?
Asked
Active
Viewed 3.8k times
22
-
What do you mean by "run" one? Do you want to simply execute the script as if in another `lua
` command-line process? Or do you want to execute it from within your script code? – Nicol Bolas Jan 07 '13 at 23:18
1 Answers
31
Usually you would use the following:
dofile("filename.lua")
But you can do this through require()
nicely. Example:
foo.lua:
io.write("Hello,")
require("bar")
bar.lua:
io.write(" ")
require("baz")
baz.lua:
io.write("World")
require("qux")
qux.lua:
print("!")
This produces the output:
Hello, World! <newline>
Notice that you do not use the .lua
extension when using require()
, but you DO need it for dofile()
.
More information here if needed.

SuperCheezGi
- 857
- 3
- 11
- 19
-
1Just want to add a note for coming readers: require " " must be a script with the extension .lua, while dofile() can be any extension. – Max Kielland Oct 09 '16 at 14:50
-
@MaxKielland are you saying that dofile() lets me attach scripts written in different languages? – Daniel Jan 11 '18 at 04:57
-
@Comrade_Comski, of course not. But as you know, you can rename any file to whatever you want. Your Lua script could be named MyGame.mod for example. But if you use require it MUST have the extension .lua, but dofile() accepts other extensions. – Max Kielland Jan 12 '18 at 07:05
-
If I write functions in my outside scripts can I call them from the main file normally or do it like `foo.function()` – Daniel Jan 13 '18 at 23:29
-
1@Comrade_Comski This comment field is a bit small to show any examples, but if you write your function in an external .lua file as a global function, you can then use `require "yourLuaFile"` (don't include the .lua in the name) to include it. All global functions will be accessible as if they were declared in your "main" file. – Max Kielland Mar 14 '18 at 19:28
-
1@Comrade_Comski I prefer to declare all the "public" functions in a local table and then return the table: `local myLib = {} function myLib.bar() end return myLib`. Then I can do like this `foo = require "mylib"` and then I can call them as `foo.bar()`. In this way I can declare local "helper" functions in my library that can't be accessed from the "main" file. – Max Kielland Mar 14 '18 at 19:29