How do I run another script from inside Lua?

lua
31,430

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.

Share:
31,430

Related videos on Youtube

SuperCheezGi
Author by

SuperCheezGi

(my about me is currently blank) click here to edit

Updated on October 29, 2020

Comments

  • SuperCheezGi
    SuperCheezGi about 2 years

    I need to execute a Lua script from inside another Lua script. How many ways are there, and how do I use them?

    • Nicol Bolas
      Nicol Bolas almost 10 years
      What do you mean by "run" one? Do you want to simply execute the script as if in another lua <ScriptName> command-line process? Or do you want to execute it from within your script code?
  • Max Kielland
    Max Kielland about 6 years
    Just want to add a note for coming readers: require " " must be a script with the extension .lua, while dofile() can be any extension.
  • Daniel
    Daniel almost 5 years
    @MaxKielland are you saying that dofile() lets me attach scripts written in different languages?
  • Max Kielland
    Max Kielland almost 5 years
    @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.
  • Daniel
    Daniel almost 5 years
    If I write functions in my outside scripts can I call them from the main file normally or do it like foo.function()
  • Max Kielland
    Max Kielland over 4 years
    @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
    Max Kielland over 4 years
    @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.