开发者

Lua C api : How to load lua files defined as modules?

I have the following lua sc开发者_如何学Cript :

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 ?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜