I can’t import tables with require

Asked

Viewed 76 times

2

I’m learning the Moon programming, and I’m learning the Require. But when I try to import a table or anything else a mistake happens.

What I’m trying to do is export a table with a function.

What I want to export:

  local calculadora = {
    somar = function(x, y)
        return x + y
    end
}

function calculadora.multiplicar(x, y)
    return x * y
end

How I’m importing:

require("calculadora")

print (calculadora.somar(1, 1))

The mistake:

lua: segundo.lua:1: module 'calculadora' not found:
    no field package.preload['calculadora']
    no file '.\calculadora.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\calculadora.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\calculadora\init.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\calculadora.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\calculadora\init.lua'
    no file 'C:\Program Files (x86)\Lua\5.1\lua\calculadora.luac'
    no file '.\calculadora.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\calculadora.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\loadall.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\calculadora.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\loadall.dll'
    no file '.\calculadora51.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\calculadora51.dll'
    no file 'C:\Program Files (x86)\Lua\5.1\clibs\calculadora51.dll'
stack traceback:
    [C]: in function 'require'
    segundo.lua:1: in main chunk
    [C]: ?
>Exit code: 1

What I do?

  • 2

    The error message is clear: Lua did not find the file calculadora.lua in none of the places listed.

1 answer

1

You ended up forgetting to export the calculator table.

Follow the example:

local calculadora = {
    somar = function(x, y)
        return x + y
    end
}

function calculadora.multiplicar(x, y)
    return x * y
end

return calculadora

Now in the file you will import, you must assign the require to a variable in order to make the call.

local calculadora = require("calculadora")

print(calculadora.somar(1, 1))

Modules and Packages

See example on page 11 of the pdf file under "Listing 15.2"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.