简体   繁体   中英

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

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 ?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM