Using modules

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:

require(blah)

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?

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)
...
end

becomes

function _M.myfunc(bla, fasel)
...
end

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

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"
    end
]]

debug.setfenv(load_module, _M)
load_module()

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

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