Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Using modules

edited June 2012 in Questions Posts: 179

This question is probably a bit basic, but I am no pro with Lua. What I want to do is use existing Lua modules with Codea. Right now, the usage for these is as such:


And in the other file there are things like local variables and local functions and so forth. Since Codea does not support require, can I simply make the whole module into a function? (basically I would just enclose the module code in a function tag)

Or do I need to try and convert it to a class?



  • Posts: 146

    Basically neither. You should be able to just copy the module you want to use into a tab (or multiple tabs, if necessary). Now, module() does some magic, in order to collect all "global" functions within the module table, you may have to emulate that. Something like this (untested, as I don't have my ipad with me) might work:

    local _G = _G
    local _M = setmetatable({}, {__index = _G})
    setfenv(1, _M)
    -- ... your module
    _G.mymodule = _M

    not sure if setfenv() is available in codea, though... if not, then omit all of the _G stuff, and prefix all global definitions in your module by _M., so that

    function myfunc(bla, fasel)


    function _M.myfunc(bla, fasel)

    the setfenv() method would be much less intrusive, though...

  • edited June 2012 Posts: 146

    ok, I've tried it: setfenv is not available from codea. But debug.setfenv is, as is loadstring. So my current solution for your problem is:

    local _G = _G
    local _M = setmetatable({}, {__index = _G})
    -- this is the module:
    local load_module = loadstring [[
        function bla()
            print "blaaaaa"
    debug.setfenv(load_module, _M)
    -- set up module table
    _G.mymod = _M

    From your program you can now call mymod.bla()

    Note that the string delimiters around your module actually have the form [====[ and ]====], for arbitrary numbers of = signs. This may be relevant if your module uses long string syntax.

  • Posts: 179

    Okay, I will give this a go. Thanks for the help.

Sign In or Register to comment.