As the title says... Chat on...

User avatar
By BillC
#37268 I'd like to write commonly used functions as modules and require them in my programs. The syntax for this seems straightforward but when I try a simple experiment it fails, what am I doing wrong?

I have two files, the first is toLoad.lua which contains;

function psomething(s)
print(s)
end

The second is loadRun.lua which contains;

local ps = require("toLoad")

ps.psomething("hello")

Executing loadRun.lua results in;

> dofile("loadRun.lua")
loadRun.lua:3: attempt to index a boolean value
stack traceback:
loadRun.lua:3: in main chunk
[C]: in function 'dofile'
stdin:1: in main chunk
User avatar
By xtal
#37278 I used this that worked ... The commented is the seredat which is loaded and compiled to
serdat .lc
Code: Select all-----------------------------   
    function uartRX(sdin)
       serdat = require("serdat")
       serdat.S1(sdin)
    end
------------------------------
--[[ local serdat = {}
    function serdat.S1(sdin)     
       if #sdin <= 2 then return end        -- suspect just crlf ??   
        xdin=string.sub(sdin,1,4)
        ydin=string.sub(sdin,1,5)           -- 000>cr
        vt.ESP = #sdin..","..ydin           
        cx = string.find(sdin,"]")             
        if string.sub(sdin,1,2)=="[c" and cx ~= nil then
           cx  = string.find(sdin,"/")
           vt.cdeg0 = string.sub(sdin,3,cx-1)
           sdin = string.sub(sdin,cx+1,#sdin)
           cx  = string.find(sdin,"/")
           vt.ppm0 = string.sub(sdin,1,cx-1)
           sdin = string.sub(sdin,cx+1,#sdin)
           cx  = string.find(sdin,"/")
           vt.apc0 = string.sub(sdin,1,cx-1)
           sdin = string.sub(sdin,cx+1,#sdin)
           cx  = string.find(sdin,"/")
           vt.ph = string.sub(sdin,1,cx-1)
           sdin = string.sub(sdin,cx+1,#sdin)         
           cx  = string.find(sdin,"]")
           vt.prb = string.sub(sdin,1,cx-1) 
           --uart.write(0,"HB\r\n")                  -
        else                           
           vt.sbuf=vt.sbuf..sdin
        end                                           
        local strt,endx,sz
        sz = #vt.sbuf
        if sz >= 730 then         
         strt,endx=string.find(vt.sbuf,"\r\n")
         vt.sbuf = string.sub(vt.sbuf,endx+1,sz)
       end   
    end     
return serdat   
--]]   

User avatar
By TerryE
#37301 This is a Q of RTFM. A required file will normally return a table but can return a function, hence
Code: Select allreturn {ps = function (s) print(s) end}
will work.
User avatar
By BillC
#37342 I see the problem now, thanks. I thought the syntax more closely resembled what you would do in Node.js. Instead you have to initialize a table with the function.

toLoad.lua should look like this;

local psomething = {}
function psomething.print(s)
print(s)
end
return psomething

... and loadRun.lua should look like this;

toLoad = require("toLoad")
toLoad.print("hello")