Need help with Lua class from module

I keep getting an “attempt to index global ‘Foo’ (a nil value)” error.

Say I want to create a class using a module named ‘Foo’. To create an instance of the Foo class, I want to call Foo:new() from main.lua. I know I have to work with metatables and all that, but the error appears to precede that stuff.

If foo.lua is basically

module(...,package.seeall)  
  
Foo = {}  
Foo\_mt = {\_\_index = Foo}  
  
function Foo:new(params)  
local self = {}  
setmetatable(self, Foo\_mt)  
...  
return self  
end  

then in main.lua, shouldn’t I be able to just write

require ("foo") --foo.lua is the doc  
  
newFoo = Foo:new()  

? [import]uid: 41305 topic_id: 9061 reply_id: 309061[/import]

Nope, should be
[lua]foo.Foo:new()[/lua]
But I advise against using the module(…,package.seeall) mehod to create modules. Just google it to see why it’s bad.
What you should do instead is use Lua tables:

myModule.lua:
[lua]local privateVar1
local privateVar2

local privateFunction1()
end

local privateFunction1()
end

return
{
publicVar1,

publicFunction1 = function()
privateFunction1()
end,

publicFunction2 = function()
end
}[/lua]
there is a slight problem with this method. You can’t use the publicvar inside publicfunction1 for example. Easily fixed:
[lua][…]
local privateFunction1()
end

local myModule = {}
myModule.publicVar1 = 5

myModule.publicFunction1 = function()
myModule.publicVar1
end

return myModule[/lua]
and then to call the module:
[lua]local myModule = require(“myModule”)
myModule.publicFunction1()[/lua]

Don’t worry about “requiring” the module in all your scripts. It only gets loaded once. I made some extensive testing on the lua require function. Maybe I’ll write a forum post explaining it.

Seth [import]uid: 51516 topic_id: 9061 reply_id: 33046[/import]

on ph, but hopefully this helps

file main.lua

require(“foo”)
testobj = foo:new()

file foo.lua

module(…,seeall)

function new()
local somevar =1
fooobject = display.newRect(params here)
fooobject.newvar = somevar
return fooobject
end


hopefully that made sense, i am using iphone and can see 4 lines :slight_smile: and cant check, all from memory, and im a noob.

the module lua is referred to as foo in main.lua, so foo:new() calls the new function in foo.lua that returns a modified display object

regards :slight_smile: [import]uid: 34945 topic_id: 9061 reply_id: 33056[/import]

I’ll give this a try, thanks. I’d be interested in what you learned about ‘require’, too. [import]uid: 41305 topic_id: 9061 reply_id: 33120[/import]

thx [import]uid: 41305 topic_id: 9061 reply_id: 33121[/import]

check out my particle fx module source code i uploaded last night, uses class modules and config objects [import]uid: 34945 topic_id: 9061 reply_id: 33147[/import]

Done. Read it here. [import]uid: 51516 topic_id: 9061 reply_id: 33218[/import]