3

I have 3 lua files, Init.lua, FreeCamera.lua and Camera.lua ,

init.lua calls require "Core.Camera.FreeCamera"

Free Camera:

module(...)
require "Core.Camera.Camera"

local M = {}
FreeCamera = M

M = Class( Camera )
function M:__constructor(x,y,z)
  self.Active = false
  self.x = x
  self.y = y
  self.z = z
end

and

module(...)

local M = {}
Camera = M

M = Class()

function M:__constructor(x,y,z)
  self.Active = false
  self.x = x
  self.y = y
  self.z = z
end

FreeCamera "inherits" Camera kind of. I am trying to require FreeCamera in my init file and I am getting this:

..\Content\Modules\Core\Camera\FreeCamera.lua:12: attempt to call global 'require' (a nil value). Any idea Why? Am I using require the right way? Clearly it is getting into FreeCamera.lua, which is great, but it gets stuck on the next require.

3 Answers 3

11

To 'import' identifiers into a module, you might write code something like the following:

local require = require
local Class = Class
local io, table, string
    = io, table, string
local type, pairs, ipairs, assert
    = type, pairs, ipairs, assert

module(...)

local Camera = require 'Core.Camera.Camera'

and so on.

The module(...) command removes (almost) everything from your global-variable namespace—it creates a new global namespace that belongs to the new module. Aside from a couple of special identifiers like _M and _G, the new namespace is empty. But local identifiers stay visible.

The local declarations make the dependencies of your module clear, and they can also communicate your intent. As a bonus, they make access to the named identifiers more efficient. So this is very good Lua style.

Sign up to request clarification or add additional context in comments.

1 Comment

perfect! i noticed this in the critique page on the module function, I am glad to know that it is good style!!
7

The module function creates a new empty environment and so require is not found when called. Try calling require before calling module.

1 Comment

That seems to have done the trick, now it says Class() is nil, but if i change that from a global, to require, it should work according to what you are saying.
0

You can:

lua module(..., package.seeall)

To import the global environment into your module. This is (presumably) the easiest solution, but may not be to your taste.

1 Comment

This is the expedient solution, but it introduces a bunch of other issues due to inclusion of the global environment inside the module's environment. The current best practice is to avoid the module() function and use local generously. Notice that in Lua 5.2, the function module() is deprecated, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.