TigerCoding
TigerCoding

Reputation: 8720

Why does my lua 'class' report an attempt to index global object error?

The following code is in a file named object.lua:

function object:new()
  local instance = {}
  setmetatable(instance, self)
  self.__index = self
  return instance
end

In a main file I have:

local object = require("object")
local obj = object:new()

The error reported is: lua ./object.lua:1: attempt to index global 'object' (a nil value)

Line #1 is the first line with 'function object:new()'

In main it's the first line (with require).

Code created from: http://www.lua.org/pil/16.1.html

Edit:

Please see this page: http://www.coronalabs.com/blog/2011/09/29/tutorial-modular-classes-in-corona/

Then search for 'james' it will be the first comment post and you can see what I'm trying to do.

Upvotes: 1

Views: 5263

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 81052

The issue here is that when the code in object.lua is run and you attempt to create the object:new function there is no object table to create it in.

Dogbert's solution works fine in that object.lua creates the object table before using it. However, it does so by explicitly creating a global and then expecting callers to have found that which is not the best solution. The amended solution provided by Nicol Bolas... that of creating a local object in object.lua and returning it is the more generally agreed upon pattern for this sort of task.

Upvotes: 1

Dogbert
Dogbert

Reputation: 222428

This works for me:

main.lua

require("object")
local obj = object:new()

object.lua

object = {}

function object:new()
    local instance = {}
    setmetatable(instance, self)
    self.__index = self
    return instance
end

You are declaring a global "object" in object.lua, not returning it, so you just need to do require("object")

Upvotes: 1

Related Questions