gleacc
gleacc

Reputation: 38

How to import a file from another folder in lua?

I am importing a file from a different folder.

Here's what I mean:

      import *c://players.lua* to *c://terrain/main.lua*

players.lua:

local user1 = "user1"

main.lua:

require "terrain/players.lua"
local spawn = 10
if user1 = false then
   user1 = true, spawn
end

I haven't getting errors because I only have a lua editor. if I get errors then I have to change it to require 'file:///c://Desktop/g/players.lua'.

Upvotes: 0

Views: 332

Answers (1)

UrNightmaree
UrNightmaree

Reputation: 1

You can use xpcall to check if the require function thrown an error

In folder1/init.lua and folder2/init.lua

return {
  printHelloWorld = function()
    print('Hello World!')
  end
}

In main.lua

-- First value that xpcall return is the status code `status: Boolean`
-- Second value is the error message `error: String`
-- Third value is the return of the function `retVal: Any`
local ok, err, lib = xpcall(function()
  return require 'folder1/init.lua'
end, function()
  return require 'folder2/init.lua'
end)

lib.printHelloWorld()

References:

Upvotes: 0

Related Questions