Reputation: 374
Edit I got this working, I'm not sure if this is the right way to do it, but this is what works right now
I just started learning Lua, and I'm trying to figure out how to pass tables between files so that I can have a more organized codespace. I have read through the book Programming in Lua, and for some reason, I can't figure out what i'm doing wrong.
The problem i'm getting is this error:
lua: Test2.lua:3: attempt to call method 'New' (a nil value)
From this code:
--Test.lua----------------
module("Test", package.seeall)
vector = require "./Hump/vector"
Bot = {}
Bot.position = vector.new(0,0)
function Bot:New(object)
object = object or {}
setmetatable(object, self)
self.__index = self
return object
end
--Test2.lua------------------
require "Test"
Bot1 = Test.Bot:New()
print(Bot1.position)
As far as I understand it, this error means that it cannot find the method new, it is effectively undefined. I thought that require imports the file in the path?
Upvotes: 0
Views: 337
Reputation: 28991
Bot
is an empty table.
local B = {} -- initialize local B with new table
Bot = B -- Bot now references the same table as B
B = { position = vector.new(0,0) } -- here you create a NEW table, B ~= Bot now
function B:New(object) -- store New function in B table, Bot still empty
So you're returning an empty table.
No need for two variables here at all.
local Bot = {
-- stuff
}
function Bot:New(object)
-- stuff
end
return Bot
Upvotes: 1