tags:

views:

74

answers:

2

Hi,

I have the following lua script :

module("modoo",package.seeall)
foo=1
bar={12,34}

Which works fine using the cli, such as :

> dofile "mod_modoo.lua"
> =modoo.foo
1
> =modoo
table: 0x86ce058

As far as I understood, it works like a table, but whenever I try loading it as a table, a nil value is pushed onto the stack. Every other table works normally.

I thought using lua_getglobal wouldn't work with modules, but I couldn't find the proper way to load it either ; how should I do it ?

+2  A: 

Instead of using module and dofile, it is better practice in Lua 5.1 to simply return a table representing your module when the script is run. All functions and variables should be declared as local within the module script so that the returned table provides the only access point and no globals from other modules are trampled. The module should be imported using require as follows.

mod_modoo.lua:

return { foo = 1,  bar = { 12, 34 } }

modoo_test.lua:

> local modoo = require "mod_modoo"

However, it is often nice to bring the module table (i.e. modoo) in as a global without explicitly assigning it. To do so, assign the module table a global reference in addition to returning it from the script. In that case, the module can be used as follows:

mod_modoo.lua:

modoo = { foo = 1,  bar = { 12, 34 } }
return modoo

modoo_test.lua:

> require "mod_modoo"
> print(modoo.foo)
1

See the Lua Module Function Critiqued article for more information on the matter.

Judge Maygarden
Why Lua 5.2? It is not released yet.
kaizer.se
Sorry, I meant Lua 5.1
Judge Maygarden
+1  A: 

Load Lua modules with require like lua.c does. See http://www.lua.org/source/5.1/lua.c.html#dolibrary

lhf